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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
Keep derived and federated video files consistent with backup history
[._.]/ Adam Eivy3cc36f0994de
diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex 9249ec678a..1aba6af6d2 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -100,7 +100,7 @@ Admission inventory (`withBackupAssetPublication`):| YouTube ingest (`youtubeIngest.js`) | Covered (#9982 partial): downloads run outside admission; the index record that first names a transcript or audio file takes the lease, and forgetting an ingest drops the record and unlinks its files under one lease || Digital twin documents and genome upload/delete (`digital-twin-documents.js`, `genome.js`) | Covered (#9982 partial): each document file or raw genome file and the meta record naming it is one lease, including deletion || Derived media index (`mediaAssetIndex/`) | Rebuilt: `media_assets` rows are excluded from snapshot dumps; database restore rebuilds atomically from disk before reopening admission, and relevant file restores refresh the mirror |-| Remaining durable owners, classified by domain in `backupAssetOwners.js` | Outstanding (#9982): video generation and image generation tails |+| Remaining durable owners, classified by domain in `backupAssetOwners.js` | Outstanding (#9982): image generation tails || Explicit file purge (`dataManager.js`, `routes/uploads.js`, `routes/attachments.js`) | Covered: single and bulk deletions hold one lease. These operator-directed removals may intentionally leave external references; admission prevents a snapshot from interleaving with the removal, not from preserving that already-deleted state || Durable replacement/deletion owners not yet classified | Outstanding (#9982) || Snapshot consistency claim (`backupAssetOwners.js`, see below) | Covered (#9982 partial) |@@ -246,8 +246,14 @@ faststart staging file before releasing the lease. A missing thumbnail retainsthe existing thumbnail-less behavior. Terminal status and notifications followthe durable commit. Caller publication latches keep committed outputs and earlierbatch members out of later failure or cancellation cleanup. Federated video-replacement/replay and derived stitch, upscale, timeline and HTML-composition-lanes remain outstanding. The derived media index is excluded from snapshot dumps: its asynchronous refresh may lag authoritative files, so preserving its rows would preserve stale file references. Both legacy and new database restores rebuild it atomically from local sidecars and video history before reopening admission. Unreadable sources or SQL failure keep recovery fenced for a same-operation retry, without replaying the dump. Full and media-selective file restores rebuild it too; a failed rebuild is reported as a reconciliation failure. This does not make unadmitted authoritative media workflows consistent.+transfers verify a staging file outside admission, then lease replacement,+poster generation and history together. A failed replacement restores the prior+clip and poster before releasing admission; replay replaces the existing row.+Derived stitch, inline and queued upscale, timeline and HTML-composition renders+produce fresh output outside admission, then lease poster and history publication+through rollback. HTML compositions commit all formats together.++The derived media index is excluded from snapshot dumps: its asynchronous refresh may lag authoritative files, so preserving its rows would preserve stale file references. Both legacy and new database restores rebuild it atomically from local sidecars and video history before reopening admission. Unreadable sources or SQL failure keep recovery fenced for a same-operation retry, without replaying the dump. Full and media-selective file restores rebuild it too; a failed rebuild is reported as a reconciliation failure. This does not make unadmitted authoritative media workflows consistent.Code Animation writes its HTML, revision trees and run artifacts before the rowthat first names them. A generated animation's HTML and the job row marking it@@ -259,7 +265,7 @@ Every production run-row write takes the lease, because the row is what firstnames the stage's frames, soundtrack WAV and Blender bake. A Blender film iscopied under a fresh name and muxed before its history entry commits under thelease. A browser render's history entry is written by the HTML-composition job-(still outstanding with video generation), so the soundtrack mux holds the lease+under admission, so the soundtrack mux holds the leaseacross its in-place install over that file, but not across the encode.A sprite's row holds metadata and workflow state (status, the frozen chroma key,diff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.jsindex f95cedeb0b..a4768d7241 100644--- a/server/lib/backupAssetOwners.js+++ b/server/lib/backupAssetOwners.js@@ -305,10 +305,10 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([modules: ['services/videoGen/generateVideoHelpers.js'],},{- // Federated replacement/replay and derived clips (stitch, upscale,- // timeline, HTML composition) have not yet proven their publication tails.+ // Federated replacement/replay keeps installation and rollback with history.+ // Derived clips lease poster/history publication after fresh renders finish.id: 'video-generation-finalize-and-derived-clips',- status: 'outstanding',+ status: 'admitted',modules: ['services/videoGen/remote.js','services/videoGen/stitchVideos.js', 'services/videoGen/upscaleVideo.js', 'services/videoGen/upscaleJob.js',diff --git a/server/services/htmlComposition/index.js b/server/services/htmlComposition/index.jsindex 5cf68c6c59..b0fb4ec479 100644--- a/server/services/htmlComposition/index.js+++ b/server/services/htmlComposition/index.js@@ -1,3 +1,4 @@+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { maintenance } from '../../lib/maintenanceAdmission.js';import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';import { cp, lstat, mkdtemp, open, realpath, rm, stat, writeFile } from 'node:fs/promises';@@ -294,56 +295,63 @@ async function renderCompositionAdmitted({ jobId, owner, audio, maxDurationSec,await page.close({ verify: true });page = null;signal.throwIfAborted();- for (const video of rendered) {- video.thumbnail = await generateThumbnail(video.outputPath, video.id, launchPlan ? { atSec: launchPlan.posterSec } : undefined);- if (!video.thumbnail) throw new Error('Composition thumbnail generation failed');- signal.throwIfAborted();- }- let launchMetadata;- if (deliveryRoot) {- // Exclusive creation refuses pre-existing files/symlinks. Publish only the- // validated snapshot, never re-read source prose after rendering.- for (const name of ['plan.md', 'storyboard.json', 'caption.txt']) {- await deliver(join(deliveryRoot, name), handle => handle.writeFile(launchAssets.get(`/${name}`)));- }- // A multi-format run names each file by its frame; a single-format- // render keeps the original video.mp4/poster.jpg names.- for (const video of rendered) {- const suffix = video.format ? `-${video.format}` : '';- for (const [source, name] of [[video.outputPath, `video${suffix}.mp4`], [join(PATHS.videoThumbnails, video.thumbnail), `poster${suffix}.jpg`]]) {- await deliver(join(deliveryRoot, name), handle => pipeline(createReadStream(source), handle.createWriteStream()));+ await withBackupAssetPublication(async () => {+ try {+ for (const video of rendered) {+ video.thumbnail = await generateThumbnail(video.outputPath, video.id, launchPlan ? { atSec: launchPlan.posterSec } : undefined);+ if (!video.thumbnail) throw new Error('Composition thumbnail generation failed');+ signal.throwIfAborted();+ }+ let launchMetadata;+ if (deliveryRoot) {+ // Exclusive creation refuses pre-existing files/symlinks. Publish only the+ // validated snapshot, never re-read source prose after rendering.+ for (const name of ['plan.md', 'storyboard.json', 'caption.txt']) {+ await deliver(join(deliveryRoot, name), handle => handle.writeFile(launchAssets.get(`/${name}`)));+ }+ // A multi-format run names each file by its frame; a single-format+ // render keeps the original video.mp4/poster.jpg names.+ for (const video of rendered) {+ const suffix = video.format ? `-${video.format}` : '';+ for (const [source, name] of [[video.outputPath, `video${suffix}.mp4`], [join(PATHS.videoThumbnails, video.thumbnail), `poster${suffix}.jpg`]]) {+ await deliver(join(deliveryRoot, name), handle => pipeline(createReadStream(source), handle.createWriteStream()));+ }+ }+ launchMetadata = { appId: launchVideo.appId, runId: launchVideo.runId,+ ...(launchVideo.sourceVideoId ? { sourceVideoId: launchVideo.sourceVideoId } : {}),+ musicTrack: musicTrack ?? null, synthesizeMusic: Boolean(synthesizeMusic),+ caption: launchAssets.get('/caption.txt').toString('utf8').trim(), posterSec: launchPlan.posterSec };}+ signal.throwIfAborted();+ // Once the shared history write starts, cancellation must be refused.+ job.committing = true;+ const createdAt = new Date().toISOString();+ // One Media History entry per format, linked by launchVideo.runId and+ // written in a single mutation so a run registers all formats or none.+ const metas = rendered.map(video => ({+ id: video.id, prompt: `HTML composition: ${sourceDirectory}`, modelId: 'html-composition', seed: 0,+ ...frameOf(video.contract), numFrames: Math.round(contract.durationSec * contract.fps),+ ...(launchMetadata ? { launchVideo: launchMetadata, appId: launchMetadata.appId, posterSec: launchPlan.posterSec } : {}),+ ...(video.sampleHistogram ? { sampleHistogram: video.sampleHistogram } : {}),+ ...(video.loudness ? { loudness: video.loudness } : {}),+ filename: video.filename, thumbnail: video.thumbnail, createdAt,+ }));+ await mutateVideoHistory(history => { history.unshift(...metas); return history; });+ success = true;+ // `id`/`filename` name a real history entry (the first format); `generationId`+ // is the job. A single-format render keeps id === generationId as before.+ // A shutter-blur render reports how many output frames took each+ // sub-frame count, so the user can see where the render time went.+ const summary = ({ id, filename, thumbnail, sampleHistogram, loudness }) => ({ id, filename, thumbnail, path: `/data/videos/${filename}`,+ ...(sampleHistogram ? { sampleHistogram } : {}), ...(loudness ? { loudness } : {}) });+ const [first] = rendered;+ result = { ...(launchMetadata ? { appId: launchMetadata.appId } : {}), generationId: jobId, ...summary(first),+ ...(formats ? { videos: rendered.map(video => ({ format: video.format, ...summary(video) })) } : {}) };+ } catch (error) {+ if (!success) for (const path of ownedPaths) await unlinkGuarded(path).catch(error => { if (error.code !== 'ENOENT') maintenance.markCurrentUnsettled(); });+ throw error;}- launchMetadata = { appId: launchVideo.appId, runId: launchVideo.runId,- ...(launchVideo.sourceVideoId ? { sourceVideoId: launchVideo.sourceVideoId } : {}),- musicTrack: musicTrack ?? null, synthesizeMusic: Boolean(synthesizeMusic),- caption: launchAssets.get('/caption.txt').toString('utf8').trim(), posterSec: launchPlan.posterSec };- }- signal.throwIfAborted();- // Once the shared history write starts, cancellation must be refused.- job.committing = true;- const createdAt = new Date().toISOString();- // One Media History entry per format, linked by launchVideo.runId and- // written in a single mutation so a run registers all formats or none.- const metas = rendered.map(video => ({- id: video.id, prompt: `HTML composition: ${sourceDirectory}`, modelId: 'html-composition', seed: 0,- ...frameOf(video.contract), numFrames: Math.round(contract.durationSec * contract.fps),- ...(launchMetadata ? { launchVideo: launchMetadata, appId: launchMetadata.appId, posterSec: launchPlan.posterSec } : {}),- ...(video.sampleHistogram ? { sampleHistogram: video.sampleHistogram } : {}),- ...(video.loudness ? { loudness: video.loudness } : {}),- filename: video.filename, thumbnail: video.thumbnail, createdAt,- }));- await mutateVideoHistory(history => { history.unshift(...metas); return history; });- success = true;- // `id`/`filename` name a real history entry (the first format); `generationId`- // is the job. A single-format render keeps id === generationId as before.- // A shutter-blur render reports how many output frames took each- // sub-frame count, so the user can see where the render time went.- const summary = ({ id, filename, thumbnail, sampleHistogram, loudness }) => ({ id, filename, thumbnail, path: `/data/videos/${filename}`,- ...(sampleHistogram ? { sampleHistogram } : {}), ...(loudness ? { loudness } : {}) });- const [first] = rendered;- result = { ...(launchMetadata ? { appId: launchMetadata.appId } : {}), generationId: jobId, ...summary(first),- ...(formats ? { videos: rendered.map(video => ({ format: video.format, ...summary(video) })) } : {}) };+ });}} catch (error) {if (job.committing) maintenance.markCurrentUnsettled();diff --git a/server/services/videoGen/derivedBackupAdmission.test.js b/server/services/videoGen/derivedBackupAdmission.test.jsnew file mode 100644index 0000000000..cc0e7f247c--- /dev/null+++ b/server/services/videoGen/derivedBackupAdmission.test.js@@ -0,0 +1,197 @@+/** Real file/history cuts through derived video service entrypoints. */+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { cp, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';+import { existsSync, writeFileSync } from 'node:fs';+import { basename, join } from 'node:path';+import { EventEmitter } from 'node:events';+import { randomUUID } from 'node:crypto';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';++const state = vi.hoisted(() => ({ bypass: false, admission: null, historyGate: null, failHistory: false, rollback: null }));+vi.mock('../../lib/fileUtils.js', async original => {+ const actual = await original();+ return makePathsProxy(actual, { dataRoot: () => lazyTempDataRoot('portos-derived-video-cut-'), overrides: {+ atomicWrite: async (path, data) => {+ 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 refused');+ }+ return actual.atomicWrite(path, data);+ },+ unlinkGuarded: async path => {+ if (state.rollback && path.startsWith(lazyTempDataRoot('portos-derived-video-cut-'))) {+ state.rollback.entered.resolve();+ await state.rollback.finish.promise;+ }+ return actual.unlinkGuarded(path);+ },+ } });+});+vi.mock('../../lib/databaseMaintenanceJournal.js', async original => ({ ...(await original()), assertDatabaseAdmission: () => {} }));+vi.mock('../../lib/backupSnapshotBoundary.js', async original => {+ const actual = await original();+ return { ...actual, withBackupAssetPublication: work => {+ state.admission?.resolve();+ return state.bypass ? work() : actual.withBackupAssetPublication(work);+ } };+});+vi.mock('../../lib/ffmpeg.js', async original => ({+ ...(await original()),+ findFfmpeg: async () => 'synthetic-ffmpeg', findFfprobe: async () => null,+ optimizeForStreaming: async () => {}, upscaleVideo2x: async () => ({ ok: true }),+ hasAudioStream: async () => false, bt709TagFilter: async () => null,+ probeVideoDuration: async () => 1,+ probeVideoStreamInfo: async () => ({ width: 2560, height: 1440, fps: 24, frameCount: 24 }),+ generateThumbnail: async (_path, id) => {+ const { PATHS } = await import('../../lib/fileUtils.js');+ await writeFile(join(PATHS.videoThumbnails, `${id}.jpg`), 'poster');+ return `${id}.jpg`;+ },+}));+vi.mock('../../lib/childProcess.js', async original => ({ ...(await original()), spawn: (_bin, args) => {+ const child = Object.assign(new EventEmitter(), { stdout: new EventEmitter(), stderr: new EventEmitter(), kill: vi.fn() });+ setImmediate(() => {+ child.emit('spawn');+ writeFileSync(args.at(-1), 'derived-video');+ child.emit('close', 0, null);+ });+ return child;+} }));+vi.mock('../../lib/sseUtils.js', async original => ({ ...(await original()), closeJobAfterDelay: () => {} }));+vi.mock('../mediaJobQueue/index.js', () => ({ enqueueJob: vi.fn() }));+vi.mock('../hfToken.js', () => ({ hfChildEnv: async () => ({}) }));+vi.mock('./renderArgs.js', () => ({ buildArgs: ({ outputPath }) => ({ bin: 'fixture', args: [outputPath] }) }));+vi.mock('../../lib/detachedSpawn.js', () => ({ spawnDetached: async (_bin, args) => {+ const child = Object.assign(new EventEmitter(), { stdout: new EventEmitter(), stderr: new EventEmitter(), pid: 101 });+ setImmediate(() => { writeFileSync(args[0], 'upscaled'); child.emit('close', 0, null); });+ return child;+} }));+vi.mock('./upscaleFfmpeg.js', () => ({+ padSourceForUpscale: vi.fn(),+ finalizeUpscaleOutput: async (_source, path) => { await writeFile(path, 'finalized upscale'); return { ok: true }; },+}));+vi.mock('./local.js', async () => await import('./history.js'));+vi.mock('../htmlComposition/browser.js', () => ({ openComposition: async () => ({+ evaluate: async () => ({ durationSec: 1, fps: 12, width: 1280, height: 720, motionBlur: 1, layout: false }),+ check: () => {}, close: async () => {},+}) }));+vi.mock('../htmlComposition/encode.js', () => ({+ encodeComposition: async (_page, _contract, path) => { await writeFile(path, 'composition'); return {}; },+ encodeContactSheet: vi.fn(), proofTimes: vi.fn(), synthesizeCompositionMusic: vi.fn(),+}));+const { PATHS } = await import('../../lib/fileUtils.js');+const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');+const { loadHistory, saveHistory } = await import('./history.js');+const { runVideoUpscale } = await import('./upscaleJob.js');+const { stitchVideos } = await import('./stitchVideos.js');+const { upscaleHistoryItem } = await import('./upscaleVideo.js');+const { renderComposition } = await import('../htmlComposition/index.js');+const { renderProject, getRenderJobStatus } = await import('../videoTimeline/local.js');+const sourceIds = [randomUUID(), randomUUID()];+const settle = () => new Promise(resolve => setImmediate(resolve));+const gates = [];+function gate() { const value = { entered: Promise.withResolvers(), finish: Promise.withResolvers() }; gates.push(value); return value; }+async function copyAssets() {+ const root = join(PATHS.data, `copy-${randomUUID()}`);+ 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'));+}+const missing = (root, rows) => rows.flatMap(row => [row.filename && join(root, 'videos', row.filename), row.thumbnail && join(root, 'posters', row.thumbnail)]).filter(path => path && !existsSync(path));+const lanes = {+ stitch: () => stitchVideos(sourceIds),+ upscale: () => upscaleHistoryItem(sourceIds[0]),+ queuedUpscale: async () => {+ const result = await runVideoUpscale({ jobId: randomUUID(), historyId: sourceIds[0], sourceFilename: `${sourceIds[0]}.mp4`, runtime: 'fixture',+ source: { width: 1280, height: 720, fps: 24, frameCount: 24 }, target: { width: 2560, height: 1440, frameCount: 24 },+ alignment: { padWidth: 0, padHeight: 0, padFrames: 0, trimFrames: 0 } });+ if (!result) throw new Error('Queued upscale failed');+ return result;+ },+ composition: () => renderComposition({ directory: 'compositions/fixture', jobId: randomUUID() }),+ timeline: async () => {+ const { jobId } = await renderProject('fixture');+ await vi.waitFor(() => expect(getRenderJobStatus(jobId).status).not.toBe('running'));+ if (getRenderJobStatus(jobId).status !== 'complete') throw new Error(getRenderJobStatus(jobId).error);+ },+};+beforeEach(async () => {+ Object.assign(state, { bypass: false, admission: null, historyGate: null, failHistory: false, rollback: null });+ await mkdir(PATHS.videos, { recursive: true });+ await mkdir(PATHS.videoThumbnails, { recursive: true });+ await mkdir(join(PATHS.data, 'compositions/fixture'), { recursive: true });+ await writeFile(join(PATHS.data, 'compositions/fixture/index.html'), '<html></html>');+ for (const id of sourceIds) await writeFile(join(PATHS.videos, `${id}.mp4`), 'source');+ await saveHistory(sourceIds.map(id => ({ id, filename: `${id}.mp4`, prompt: 'Synthetic source', width: 1280, height: 720, fps: 24, numFrames: 24 })));+ await writeFile(join(PATHS.data, 'video-projects.json'), JSON.stringify([{ id: 'fixture', name: 'Synthetic timeline', clips: [{ clipId: sourceIds[0], inSec: 0, outSec: 1 }] }]));+});+afterEach(async () => {+ for (const value of gates.splice(0)) value.finish.resolve();+ await rm(PATHS.videos, { recursive: true, force: true });+ await rm(PATHS.videoThumbnails, { recursive: true, force: true });+});+afterAll(cleanupTempDataRoots);++for (const [name, run] of Object.entries(lanes)) describe(`${name} backup publication`, () => {+ it('holds a completed producer out of a cut; bypass demonstrates dangling copied records', async () => {+ let cut = await acquireBackupSnapshotCut();+ let operation;+ try {+ const copied = await copyAssets();+ state.admission = Promise.withResolvers();+ operation = run();+ await state.admission.promise;+ await settle();+ expect(await copyHistory(copied)).toHaveLength(2);+ } finally { cut(); await operation; }+ // Run a second fresh output with admission bypassed after copying assets.+ state.bypass = true;+ const copied = await copyAssets();+ await run();+ expect(missing(copied, await copyHistory(copied)).length).toBeGreaterThan(0);+ });++ it('drains history commit before copying a complete file/record pair', async () => {+ const blocked = gate(); state.historyGate = blocked;+ const operation = run();+ await blocked.entered.promise;+ let acquired = false;+ const cutting = acquireBackupSnapshotCut().then(cut => { acquired = true; return cut; });+ try {+ await settle(); expect(acquired).toBe(false);+ blocked.finish.resolve(); await operation;+ const cut = await cutting;+ try {+ const copied = await copyAssets();+ const rows = await copyHistory(copied);+ expect(rows).toHaveLength(3);+ expect(missing(copied, rows)).toEqual([]);+ } finally { cut(); }+ } finally { blocked.finish.resolve(); await operation.catch(() => {}); (await cutting)(); }+ });++ it('drains failed-history rollback before a cut sees the discarded output', async () => {+ state.failHistory = true;+ const blocked = gate(); state.rollback = blocked;+ const operation = run().then(() => null, error => error);+ await blocked.entered.promise;+ let acquired = false;+ const cutting = acquireBackupSnapshotCut().then(cut => { acquired = true; return cut; });+ try {+ await settle(); expect(acquired).toBe(false);+ blocked.finish.resolve(); expect(await operation).toBeInstanceOf(Error);+ const cut = await cutting;+ try {+ expect(await loadHistory()).toHaveLength(2);+ expect((await readdir(PATHS.videos)).sort()).toEqual(sourceIds.map(id => `${id}.mp4`).sort());+ expect(await readdir(PATHS.videoThumbnails)).toEqual([]);+ } finally { cut(); }+ } finally { blocked.finish.resolve(); await operation.catch(() => {}); (await cutting)(); }+ });+});diff --git a/server/services/videoGen/remote.js b/server/services/videoGen/remote.jsindex 458b88d5e8..b54038f7d7 100644--- a/server/services/videoGen/remote.js+++ b/server/services/videoGen/remote.js@@ -13,6 +13,9 @@*/import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { copyFile, mkdtemp, rm, unlink } from 'node:fs/promises';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { z } from 'zod';import { PATHS } from '../../lib/fileUtils.js';import { generateThumbnail, optimizeForStreaming } from '../../lib/ffmpeg.js';@@ -66,6 +69,31 @@ const executor = createRemoteMediaExecutor({// `<jobId>.mp4` is videoGen/local.js's own filename shape, which is what the// provider-side result guard and the local history row both key on.resolveDestination: ({ jobId }) => ({ dir: PATHS.videos, filename: `${jobId}.mp4` }),+ publishResult: (work, { path, jobId }) => withBackupAssetPublication(async () => {+ // Replay can replace an already referenced clip and poster. Keep both old+ // files until the history commit succeeds, and restore them on failure.+ const scratch = await mkdtemp(join(tmpdir(), 'portos-video-replay-'));+ const originals = [];+ try {+ for (const [index, target] of [path, join(PATHS.videoThumbnails, `${jobId}.jpg`)].entries()) {+ const backup = join(scratch, String(index));+ try {+ await copyFile(target, backup);+ originals.push({ target, backup });+ } catch (error) {+ if (error.code !== 'ENOENT') throw error;+ originals.push({ target, backup: null });+ }+ }+ try { return await work(); } catch (error) {+ for (const { target, backup } of originals) {+ if (backup) await copyFile(backup, target);+ else await unlink(target).catch(error => { if (error.code !== 'ENOENT') throw error; });+ }+ throw error;+ }+ } finally { await rm(scratch, { recursive: true, force: true }); }+ }),async finalize({ jobId, path, filename, request, remoteJob, peerId, renderStartedAtMs }) {// Both ffmpeg passes are best-effort by construction (they no-op when// ffmpeg is absent), exactly as the local finalize path treats them — a@@ -78,6 +106,8 @@ const executor = createRemoteMediaExecutor({const loraFilenames = Array.isArray(request.loraFilenames) ? request.loraFilenames : [];const loraLicenses = await readLoraLicensesByFilename(loraFilenames);await mutateVideoHistory((history) => {+ // A reconciled completion replaces its prior row rather than duplicating it.+ history = history.filter(entry => entry.id !== jobId);history.unshift({id: jobId,prompt: request.prompt,diff --git a/server/services/videoGen/remote.test.js b/server/services/videoGen/remote.test.jsindex 9e058a4a0e..71269c4f59 100644--- a/server/services/videoGen/remote.test.js+++ b/server/services/videoGen/remote.test.js@@ -1,6 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { createHash } from 'node:crypto';-import { mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { cp, mkdir, readFile, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -8,7 +9,16 @@ let tempVideoDir;const transport = vi.hoisted(() => ({ fetch: vi.fn() }));const federation = vi.hoisted(() => ({ resolve: vi.fn(), peers: [] }));const ffmpeg = vi.hoisted(() => ({ thumbnail: vi.fn(), faststart: vi.fn() }));-const historyState = vi.hoisted(() => ({ rows: [] }));+const historyState = vi.hoisted(() => ({ rows: [], gate: null, fail: false }));+const publication = vi.hoisted(() => ({ bypass: false, entered: null }));+vi.mock('../../lib/backupSnapshotBoundary.js', async original => {+ const actual = await original();+ return { ...actual, withBackupAssetPublication: work => {+ publication.entered?.resolve();+ return publication.bypass ? work() : actual.withBackupAssetPublication(work);+ } };+});+vi.mock('../../lib/databaseMaintenanceJournal.js', async original => ({ ...(await original()), assertDatabaseAdmission: () => {} }));vi.mock('../../lib/fileUtils.js', async () => {const actual = await vi.importActual('../../lib/fileUtils.js');@@ -16,7 +26,7 @@ vi.mock('../../lib/fileUtils.js', async () => {...actual,PATHS: new Proxy(actual.PATHS, {get(target, key) {- if (key === 'videos') return tempVideoDir;+ if (key === 'videos' || key === 'videoThumbnails') return tempVideoDir;return target[key];},}),@@ -33,7 +43,13 @@ vi.mock('../../lib/ffmpeg.js', () => ({}));vi.mock('./history.js', () => ({- mutateVideoHistory: async (mutator) => { historyState.rows = await mutator(historyState.rows); },+ mutateVideoHistory: async (mutator) => {+ historyState.gate?.entered.resolve();+ if (historyState.gate) await historyState.gate.finish.promise;+ if (historyState.fail) throw new Error('history refused');+ historyState.rows = await mutator(structuredClone(historyState.rows));+ await writeFile(join(tempVideoDir, 'history.json'), JSON.stringify(historyState.rows));+ },}));vi.mock('../federatedMediaConsumer.js', () => ({@@ -133,6 +149,9 @@ function captureTerminal(jobId) {beforeEach(() => {tempVideoDir = mkdtempSync(join(tmpdir(), 'remote-video-test-'));historyState.rows = [];+ historyState.gate = null; historyState.fail = false;+ publication.bypass = false; publication.entered = null;+ writeFileSync(join(tempVideoDir, 'history.json'), '[]');federation.peers = [peer];federation.resolve.mockReset().mockResolvedValue({peer,@@ -338,3 +357,93 @@ describe('federated video consumer adapter', () => {expect(outcome.event).not.toHaveProperty('remoteRecoverySettlement');});});+++describe('federated video replacement backup cut', () => {+ const bytes = Buffer.from('verified replacement');+ const video = () => join(tempVideoDir, `${LOCAL_JOB_ID}.mp4`);+ const poster = () => join(tempVideoDir, `${LOCAL_JOB_ID}.jpg`);+ async function prepare() {+ await writeFile(video(), 'original video');+ await writeFile(poster(), 'original poster');+ historyState.rows = [{ id: LOCAL_JOB_ID, filename: `${LOCAL_JOB_ID}.mp4`, thumbnail: `${LOCAL_JOB_ID}.jpg`, prompt: 'Original' }];+ await writeFile(join(tempVideoDir, 'history.json'), JSON.stringify(historyState.rows));+ ffmpeg.thumbnail.mockImplementation(async () => { await writeFile(poster(), 'replacement poster'); return `${LOCAL_JOB_ID}.jpg`; });+ transport.fetch.mockImplementation(async (url) => {+ if (url.endsWith('/result')) return new Response(bytes, { headers: {+ 'Content-Length': String(bytes.length), 'Content-Type': 'video/mp4', 'X-Content-SHA256': sha256(bytes),+ } });+ return jsonResponse(providerJob('completed', { result: {+ available: true, mimeType: 'video/mp4', sizeBytes: bytes.length, sha256: sha256(bytes),+ downloadUrl: '/unused', engine: 'local', modelId: 'ltx2', durationSec: 1,+ } }), 202);+ });+ }+ async function copyAssets() {+ const target = join(tempVideoDir, 'copied');+ await mkdir(target, { recursive: true });+ await cp(video(), join(target, 'clip.mp4'));+ await cp(poster(), join(target, 'poster.jpg'));+ return target;+ }+ async function copyRows(target) {+ await cp(join(tempVideoDir, 'history.json'), join(target, 'history.json'));+ return JSON.parse(await readFile(join(target, 'history.json'), 'utf8'));+ }+ const turn = () => new Promise(resolve => setImmediate(resolve));++ it('holds same-name replacement outside a cut and proves a mismatched copied pair when bypassed', async () => {+ const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');+ await prepare();+ const cut = await acquireBackupSnapshotCut();+ let run;+ try {+ const copied = await copyAssets();+ publication.entered = Promise.withResolvers();+ run = generateVideo(params());+ await publication.entered.promise; await turn();+ expect(await readFile(video(), 'utf8')).toBe('original video');+ expect((await copyRows(copied))[0].prompt).toBe('Original');+ } finally { cut(); await run; }+ await prepare();+ const copied = await copyAssets();+ publication.bypass = true;+ await generateVideo(params());+ expect((await copyRows(copied))[0].prompt).not.toBe('Original');+ expect(await readFile(join(copied, 'clip.mp4'), 'utf8')).toBe('original video');+ });++ for (const fail of [false, true]) it(`drains replacement ${fail ? 'rollback' : 'commit'} before copying`, async () => {+ const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');+ await prepare();+ historyState.fail = fail;+ const gate = { entered: Promise.withResolvers(), finish: Promise.withResolvers() };+ historyState.gate = gate;+ const run = generateVideo(params());+ await gate.entered.promise;+ let acquired = false;+ const cutting = acquireBackupSnapshotCut().then(cut => { acquired = true; return cut; });+ try {+ await turn(); expect(acquired).toBe(false);+ gate.finish.resolve(); await run;+ const cut = await cutting;+ try {+ const copied = await copyAssets();+ const rows = await copyRows(copied);+ expect(rows).toHaveLength(1);+ expect(await readFile(join(copied, 'clip.mp4'), 'utf8')).toBe(fail ? 'original video' : bytes.toString());+ expect(await readFile(join(copied, 'poster.jpg'), 'utf8')).toBe(fail ? 'original poster' : 'replacement poster');+ expect(rows[0].prompt === 'Original').toBe(fail);+ } finally { cut(); }+ } finally { gate.finish.resolve(); }+ });++ it('replays a matching completed result without duplicate history or another transfer', async () => {+ await prepare();+ await generateVideo(params());+ const calls = transport.fetch.mock.calls.filter(([url]) => url.endsWith('/result')).length;+ await generateVideo(params());+ expect(historyState.rows).toHaveLength(1);+ expect(transport.fetch.mock.calls.filter(([url]) => url.endsWith('/result'))).toHaveLength(calls);+ });+});diff --git a/server/services/videoGen/stitchVideos.js b/server/services/videoGen/stitchVideos.jsindex 6d15991a54..a2bd139cb1 100644--- a/server/services/videoGen/stitchVideos.js+++ b/server/services/videoGen/stitchVideos.js@@ -1,3 +1,5 @@+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';+import { discardUnpublishedVideo } from './generateVideoHelpers.js';/** Lossless hand stitching and trim-aware chained-video assembly. */import { existsSync } from 'fs';@@ -186,7 +188,8 @@ export async function stitchVideos(videoIds, opts = {}) {// inputs were never re-encoded, so they're still in codec lockstep and// the stream-copy concat below can salvage the clip. The cost is the// echoed context replaying at each trimmed seam.- console.log(`⚠️ Trimmed concat failed (${failure.message}) — falling back to a stream copy; ${cutCount} seam(s) will repeat their context`);+ committed = true;+ console.log(`⚠️ Trimmed concat failed (${failure.message}) — falling back to a stream copy; ${cutCount} seam(s) will repeat their context`);trimsApplied = false;}}@@ -201,95 +204,104 @@ export async function stitchVideos(videoIds, opts = {}) {if (listFileWritten) await unlinkGuarded(listFile).catch(() => {});}- const thumb = await generateThumbnail(outPath, id);- const stitchedMeta = {- id,- prompt: promptOverride != null- ? promptOverride- : `Stitched: ${videos.map((v) => v.prompt).join(' + ')}`,- modelId: videos[0].modelId,- seed: videos[0].seed ?? 0,- width: videos[0].width,- height: videos[0].height,- // What each input actually contributes. A measured plan wins over the- // entry's own `numFrames` either way — but when the cuts didn't make it- // into the output, the input contributes its WHOLE measured length- // (`startFrame + frames`), not the trimmed length we asked for.- numFrames: videos.reduce((sum, v, i) => {- const plan = trimPlan[i];- const measured = plan?.frames == null- ? null- : (trimsApplied ? plan.frames : plan.startFrame + plan.frames);- return sum + (measured ?? v.numFrames ?? 0);- }, 0),- fps: videos[0].fps,- filename: outFilename,- thumbnail: thumb,- createdAt: new Date().toISOString(),- ...chainRenderTiming(videos, historyKey),- [historyKey]: videoIds,- ...(Array.isArray(chunkPrompts) ? { chunkPrompts } : {}),- // The stitched clip is the chain's visible history row, so it must carry- // the same render controls and provenance as the hidden chunks. Preserve- // meaningful falsey values (guidance 0, audio enabled, empty conditioning)- // while keeping legacy/partial entries free of explicit undefined fields.- ...Object.fromEntries([- 'steps',- 'guidanceScale',- 'tiling',- 'disableAudio',- 'mode',- 'textEncoderId',- 'imageStrength',- 'i2vReferenceMode',- 'conditioning',- 'renderInputsVersion',- // Speed profile (#4875) — the REQUESTED schedule and what the runner- // actually applied. Inherited for a stronger reason than the dials above:- // a chain's chunk entries are written `hidden: true`, so this stitched- // record is the ONLY one the user ever sees. Without it the lightbox's- // "Speed profile" row never renders for a chained render — including a- // chain whose TeaCache or adapter was unavailable, which is exactly the- // silent speed claim the feature exists to prevent — and a Remix quietly- // reverts to Quality. A chain applies its profile to every chunk or to- // none (resolveVideoSpeedProfileForModes), so videos[0] speaks for all.- 'speedProfileId',- 'speedProfileApplied',- // Draft decode REQUEST (#5423) — chain-wide by construction: every chunk- // is submitted with the same `draftDecode`, and the gate that resolves it- // is mode-independent, so videos[0] speaks for all. Inherited for the same- // reason as the speed profile above — the chunks are hidden, so without it- // the stitched record could never say the clip was decoded at preview- // fidelity, and a Remix would quietly revert to Full.- 'draftDecode',- // Block-streaming REQUEST (#6499) — same reasoning as draftDecode above:- // every chunk is submitted with the same streamingMode, and the chunks- // are hidden, so without inheriting it the stitched record could never- // show which mode the chain was rendered with.- 'streamingMode',- ].flatMap((key) => videos[0][key] === undefined ? [] : [[key, videos[0][key]]])),- // The draft-decode OUTCOME is decided per child process — the runner falls- // back to the full decoder on any load failure — so unlike the request- // above, videos[0] does NOT speak for the chain. Inherited only when every- // chunk agrees; on a mixed chain the field is omitted, which the lightbox- // already renders as "outcome not reported". Asserting chunk 0's verdict- // over a clip whose later chunks decoded differently would be exactly the- // false fidelity claim this field exists to prevent.- ...unanimousDraftDecodeOutcome(videos),- ...unanimousStreamingPolicyOutcome(videos),- // Inherit applied LoRAs from the first constituent clip (a chunk chain- // shares one LoRA set across all chunks), so the visible stitched entry- // round-trips LoRAs on Remix the same way a single render does — mirrors- // how modelId/seed/width above are taken from videos[0].- ...(Array.isArray(videos[0].loraFilenames) && videos[0].loraFilenames.length ? {- loraFilenames: videos[0].loraFilenames,- loraScales: videos[0].loraScales,- } : {}),- };- // Serialized append against the shared history tail (re-reads the freshest- // list inside the mutator) so a concurrent download/render write can't drop- // this stitched entry.- await mutateVideoHistory((history) => { history.unshift(stitchedMeta); return history; });- console.log(`🎬 Stitched ${videos.length} videos → ${outFilename}`);- return stitchedMeta;+ return withBackupAssetPublication(async () => {+ let committed = false;+ try {+ const thumb = await generateThumbnail(outPath, id);+ const stitchedMeta = {+ id,+ prompt: promptOverride != null+ ? promptOverride+ : `Stitched: ${videos.map((v) => v.prompt).join(' + ')}`,+ modelId: videos[0].modelId,+ seed: videos[0].seed ?? 0,+ width: videos[0].width,+ height: videos[0].height,+ // What each input actually contributes. A measured plan wins over the+ // entry's own `numFrames` either way — but when the cuts didn't make it+ // into the output, the input contributes its WHOLE measured length+ // (`startFrame + frames`), not the trimmed length we asked for.+ numFrames: videos.reduce((sum, v, i) => {+ const plan = trimPlan[i];+ const measured = plan?.frames == null+ ? null+ : (trimsApplied ? plan.frames : plan.startFrame + plan.frames);+ return sum + (measured ?? v.numFrames ?? 0);+ }, 0),+ fps: videos[0].fps,+ filename: outFilename,+ thumbnail: thumb,+ createdAt: new Date().toISOString(),+ ...chainRenderTiming(videos, historyKey),+ [historyKey]: videoIds,+ ...(Array.isArray(chunkPrompts) ? { chunkPrompts } : {}),+ // The stitched clip is the chain's visible history row, so it must carry+ // the same render controls and provenance as the hidden chunks. Preserve+ // meaningful falsey values (guidance 0, audio enabled, empty conditioning)+ // while keeping legacy/partial entries free of explicit undefined fields.+ ...Object.fromEntries([+ 'steps',+ 'guidanceScale',+ 'tiling',+ 'disableAudio',+ 'mode',+ 'textEncoderId',+ 'imageStrength',+ 'i2vReferenceMode',+ 'conditioning',+ 'renderInputsVersion',+ // Speed profile (#4875) — the REQUESTED schedule and what the runner+ // actually applied. Inherited for a stronger reason than the dials above:+ // a chain's chunk entries are written `hidden: true`, so this stitched+ // record is the ONLY one the user ever sees. Without it the lightbox's+ // "Speed profile" row never renders for a chained render — including a+ // chain whose TeaCache or adapter was unavailable, which is exactly the+ // silent speed claim the feature exists to prevent — and a Remix quietly+ // reverts to Quality. A chain applies its profile to every chunk or to+ // none (resolveVideoSpeedProfileForModes), so videos[0] speaks for all.+ 'speedProfileId',+ 'speedProfileApplied',+ // Draft decode REQUEST (#5423) — chain-wide by construction: every chunk+ // is submitted with the same `draftDecode`, and the gate that resolves it+ // is mode-independent, so videos[0] speaks for all. Inherited for the same+ // reason as the speed profile above — the chunks are hidden, so without it+ // the stitched record could never say the clip was decoded at preview+ // fidelity, and a Remix would quietly revert to Full.+ 'draftDecode',+ // Block-streaming REQUEST (#6499) — same reasoning as draftDecode above:+ // every chunk is submitted with the same streamingMode, and the chunks+ // are hidden, so without inheriting it the stitched record could never+ // show which mode the chain was rendered with.+ 'streamingMode',+ ].flatMap((key) => videos[0][key] === undefined ? [] : [[key, videos[0][key]]])),+ // The draft-decode OUTCOME is decided per child process — the runner falls+ // back to the full decoder on any load failure — so unlike the request+ // above, videos[0] does NOT speak for the chain. Inherited only when every+ // chunk agrees; on a mixed chain the field is omitted, which the lightbox+ // already renders as "outcome not reported". Asserting chunk 0's verdict+ // over a clip whose later chunks decoded differently would be exactly the+ // false fidelity claim this field exists to prevent.+ ...unanimousDraftDecodeOutcome(videos),+ ...unanimousStreamingPolicyOutcome(videos),+ // Inherit applied LoRAs from the first constituent clip (a chunk chain+ // shares one LoRA set across all chunks), so the visible stitched entry+ // round-trips LoRAs on Remix the same way a single render does — mirrors+ // how modelId/seed/width above are taken from videos[0].+ ...(Array.isArray(videos[0].loraFilenames) && videos[0].loraFilenames.length ? {+ loraFilenames: videos[0].loraFilenames,+ loraScales: videos[0].loraScales,+ } : {}),+ };+ // Serialized append against the shared history tail (re-reads the freshest+ // list inside the mutator) so a concurrent download/render write can't drop+ // this stitched entry.+ await mutateVideoHistory((history) => { history.unshift(stitchedMeta); return history; });+ committed = true;+ console.log(`🎬 Stitched ${videos.length} videos → ${outFilename}`);+ return stitchedMeta;+ } catch (error) {+ if (!committed) await discardUnpublishedVideo({ jobId: id, outputPath: outPath });+ throw error;+ }+ });}diff --git a/server/services/videoGen/upscaleJob.js b/server/services/videoGen/upscaleJob.jsindex 158a6ae9e9..ebdc401518 100644--- a/server/services/videoGen/upscaleJob.js+++ b/server/services/videoGen/upscaleJob.js@@ -1,3 +1,4 @@+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';/*** Generative video upscale — the media-job lifecycle (#6511).*@@ -430,58 +431,65 @@ export async function runVideoUpscale({throw new ServerError(`Failed to finish the upscaled clip: ${finalized.reason}`, { status: 500, code: 'UPSCALE_MUX_FAILED' });}- // Provenance is MEASURED off the deliverable, not assumed from the plan —- // a generative render is the one upscale method whose output can legally- // differ from 2× the source, so a recorded guess would be a lie.- const [measured, duration] = await Promise.all([- probeVideoStreamInfo(deliverablePath),- probeVideoDuration(deliverablePath),- ]);- const thumbnail = await generateThumbnail(deliverablePath, newId);- // Tracked so a failure between here and the history write cannot leave a- // poster for a clip that does not exist.- thumbnailPath = thumbnail ? safeUnder(PATHS.videoThumbnails, thumbnail) : null;- const newEntry = {- ...omitRenderTiming(item),- id: newId,- filename: newFilename,- thumbnail,- createdAt: new Date().toISOString(),- width: measured.width ?? source.width * UPSCALE_SCALE,- height: measured.height ?? source.height * UPSCALE_SCALE,- fps: measured.fps ?? source.fps,- numFrames: measured.frameCount ?? source.frameCount,- duration,- seed,- upscaledFrom: item.id,- upscaleMethod: 'ltx',- upscaleRuntime: runtime,- upscaleAdapter: adapterKey,- // Measured by the runner off the weight it fused (the rule it enforced),- // and — in the same shape a plain render's row carries — the exact- // ltx/mlx/torch + chip + OS stack this clip rendered on. Both are absent- // sentinels when the runner did not report them, never a guessed value.- ...(rendered.referenceDownscale !== null ? { upscaleReferenceDownscale: rendered.referenceDownscale } : {}),- ...(rendered.runtime ? { runtime: rendered.runtime } : {}),- // What the grid actually required of this source, kept beside the result- // so a reader can tell a padded render from a conforming one.- upscaleAlignment: {- padWidth: alignment.padWidth,- padHeight: alignment.padHeight,- padFrames: alignment.padFrames,- trimFrames: alignment.trimFrames,- },- prompt: upscaledPrompt(item.prompt),- hidden: false,- ...renderTimingFields(renderStartedAtMs),- };- await mutateVideoHistory((h) => { h.unshift(newEntry); return h; });- console.log(`✅ Upscaled [${newId.slice(0, 8)}]: ${newFilename} (${newEntry.width}×${newEntry.height}, ${Math.round((newEntry.renderMs ?? 0) / 1000)}s)`);- result = newEntry;+ await withBackupAssetPublication(async () => {+ try {+ // Provenance is MEASURED off the deliverable, not assumed from the plan —+ // a generative render is the one upscale method whose output can legally+ // differ from 2× the source, so a recorded guess would be a lie.+ const [measured, duration] = await Promise.all([+ probeVideoStreamInfo(deliverablePath),+ probeVideoDuration(deliverablePath),+ ]);+ const thumbnail = await generateThumbnail(deliverablePath, newId);+ // Tracked so a failure between here and the history write cannot leave a+ // poster for a clip that does not exist.+ thumbnailPath = thumbnail ? safeUnder(PATHS.videoThumbnails, thumbnail) : null;+ const newEntry = {+ ...omitRenderTiming(item),+ id: newId,+ filename: newFilename,+ thumbnail,+ createdAt: new Date().toISOString(),+ width: measured.width ?? source.width * UPSCALE_SCALE,+ height: measured.height ?? source.height * UPSCALE_SCALE,+ fps: measured.fps ?? source.fps,+ numFrames: measured.frameCount ?? source.frameCount,+ duration,+ seed,+ upscaledFrom: item.id,+ upscaleMethod: 'ltx',+ upscaleRuntime: runtime,+ upscaleAdapter: adapterKey,+ // Measured by the runner off the weight it fused (the rule it enforced),+ // and — in the same shape a plain render's row carries — the exact+ // ltx/mlx/torch + chip + OS stack this clip rendered on. Both are absent+ // sentinels when the runner did not report them, never a guessed value.+ ...(rendered.referenceDownscale !== null ? { upscaleReferenceDownscale: rendered.referenceDownscale } : {}),+ ...(rendered.runtime ? { runtime: rendered.runtime } : {}),+ // What the grid actually required of this source, kept beside the result+ // so a reader can tell a padded render from a conforming one.+ upscaleAlignment: {+ padWidth: alignment.padWidth,+ padHeight: alignment.padHeight,+ padFrames: alignment.padFrames,+ trimFrames: alignment.trimFrames,+ },+ prompt: upscaledPrompt(item.prompt),+ hidden: false,+ ...renderTimingFields(renderStartedAtMs),+ };+ await mutateVideoHistory((h) => { h.unshift(newEntry); return h; });+ result = newEntry;+ console.log(`✅ Upscaled [${newId.slice(0, 8)}]: ${newFilename} (${newEntry.width}×${newEntry.height}, ${Math.round((newEntry.renderMs ?? 0) / 1000)}s)`);+ } catch (error) {+ if (!result) for (const path of [deliverablePath, join(PATHS.videoThumbnails, `${newId}.jpg`)]) await removeOwnedFile(path);+ throw error;+ }+ });} catch (err) {// The history row is written LAST, so nothing here can orphan one — only a// partial file can exist, and it is removed before the failure is reported.- for (const path of [deliverablePath, thumbnailPath]) {+ for (const path of result ? [] : [deliverablePath, thumbnailPath]) {await removeOwnedFile(path);}const reason = entry.canceled ? 'Canceled while running' : (err.message || 'Upscale failed');diff --git a/server/services/videoGen/upscaleVideo.js b/server/services/videoGen/upscaleVideo.jsindex 989eb0b629..6805603cd4 100644--- a/server/services/videoGen/upscaleVideo.js+++ b/server/services/videoGen/upscaleVideo.js@@ -1,3 +1,5 @@+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';+import { discardUnpublishedVideo } from './generateVideoHelpers.js';/** Non-destructive 2x upscaling for video-history items. */import { existsSync } from 'fs';@@ -272,39 +274,48 @@ export async function upscaleHistoryItem(historyId, options = {}) {await unlinkGuarded(newPath).catch(() => {});throw new ServerError(`Upscale failed: ${result.reason}`, { status: 500, code: 'FFMPEG_FAILED' });}- const thumbnail = await generateThumbnail(newPath, newId);- // Build the new history entry from the original, but bump dimensions and- // tag with `upscaledFrom: <id>` + a reusable suffix on the prompt so the- // gallery row reads as "<original prompt> (2×)".- const newEntry = {- // Strip before the spread rather than relying on the override below to win:- // `renderTimingFields` reports `{}` when it can't measure the span, and an- // override that contributes no keys would silently leave the SOURCE render's- // duration on a row that only ran an ffmpeg pass.- ...omitRenderTiming(item),- id: newId,- filename: newFilename,- width: (Number(item.width) || 0) * UPSCALE_SCALE,- height: (Number(item.height) || 0) * UPSCALE_SCALE,- thumbnail,- createdAt: new Date().toISOString(),- upscaledFrom: item.id,- // Provenance (#6509): Lanczos is deterministic and seedless, and runs as an- // ffmpeg filter rather than on a BYOV runtime. Recording both explicitly- // keeps `upscaleMethod`/`upscaleRuntime` non-null on every upscaled row, so- // a reader never has to infer "the old one" from an absent key once the- // generative method starts writing its own.- upscaleMethod: method,- upscaleRuntime: LANCZOS_RUNTIME_ID,- prompt: item.prompt ? `${item.prompt} (2×)` : '(upscaled 2×)',- // Drop hidden so the upscaled version surfaces in the visible gallery- // even when the source clip was hidden.- hidden: false,- ...renderTimingFields(renderStartedAtMs),- };- // Serialized append (re-reads inside the mutator) so a concurrent- // download/render write can't drop the upscaled entry.- await mutateVideoHistory((history) => { history.unshift(newEntry); return history; });- console.log(`✅ Upscaled [${newId.slice(0, 8)}]: ${newFilename} (${newEntry.width}×${newEntry.height})`);- return newEntry;+ return withBackupAssetPublication(async () => {+ let committed = false;+ try {+ const thumbnail = await generateThumbnail(newPath, newId);+ // Build the new history entry from the original, but bump dimensions and+ // tag with `upscaledFrom: <id>` + a reusable suffix on the prompt so the+ // gallery row reads as "<original prompt> (2×)".+ const newEntry = {+ // Strip before the spread rather than relying on the override below to win:+ // `renderTimingFields` reports `{}` when it can't measure the span, and an+ // override that contributes no keys would silently leave the SOURCE render's+ // duration on a row that only ran an ffmpeg pass.+ ...omitRenderTiming(item),+ id: newId,+ filename: newFilename,+ width: (Number(item.width) || 0) * UPSCALE_SCALE,+ height: (Number(item.height) || 0) * UPSCALE_SCALE,+ thumbnail,+ createdAt: new Date().toISOString(),+ upscaledFrom: item.id,+ // Provenance (#6509): Lanczos is deterministic and seedless, and runs as an+ // ffmpeg filter rather than on a BYOV runtime. Recording both explicitly+ // keeps `upscaleMethod`/`upscaleRuntime` non-null on every upscaled row, so+ // a reader never has to infer "the old one" from an absent key once the+ // generative method starts writing its own.+ upscaleMethod: method,+ upscaleRuntime: LANCZOS_RUNTIME_ID,+ prompt: item.prompt ? `${item.prompt} (2×)` : '(upscaled 2×)',+ // Drop hidden so the upscaled version surfaces in the visible gallery+ // even when the source clip was hidden.+ hidden: false,+ ...renderTimingFields(renderStartedAtMs),+ };+ // Serialized append (re-reads inside the mutator) so a concurrent+ // download/render write can't drop the upscaled entry.+ await mutateVideoHistory((history) => { history.unshift(newEntry); return history; });+ committed = true;+ console.log(`✅ Upscaled [${newId.slice(0, 8)}]: ${newFilename} (${newEntry.width}×${newEntry.height})`);+ return newEntry;+ } catch (error) {+ if (!committed) await discardUnpublishedVideo({ jobId: newId, outputPath: newPath });+ throw error;+ }+ });}diff --git a/server/services/videoTimeline/local.js b/server/services/videoTimeline/local.jsindex b5e5a3472c..a5cd1b771b 100644--- a/server/services/videoTimeline/local.js+++ b/server/services/videoTimeline/local.js@@ -1,3 +1,5 @@+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';+import { discardUnpublishedVideo } from '../videoGen/generateVideoHelpers.js';import { maintenance } from '../../lib/maintenanceAdmission.js';/*** Video Timeline — non-linear editor backend.@@ -722,31 +724,39 @@ async function renderAdmittedProject(projectId, { posterSec } = {}, permit) {permit.finish();return;}+ const thumb = await withBackupAssetPublication(async () => {+ try {+ // The encode args already include -movflags +faststart, so no separate+ // remux pass is needed here.+ const thumb = await generateThumbnail(outputPath, jobId, { atSec: posterSec });++ // Push to existing video history with a timelineProjectId flag so the+ // Media History page picks it up alongside generated clips.+ const renderedNumFrames = Math.round(totalDuration * (fps || 24));+ const meta = {+ id: jobId,+ prompt: `Timeline: ${project.name}`,+ modelId: 'timeline',+ seed: 0,+ width: canonW,+ height: canonH,+ numFrames: renderedNumFrames,+ fps: fps || 24,+ filename,+ thumbnail: thumb,+ createdAt: new Date().toISOString(),+ timelineProjectId: projectId,+ };+ // Serialized append through the single shared history tail so a concurrent+ // download/render/timeline write can't clobber this entry.+ await mutateVideoHistory((history) => { history.unshift(meta); return history; });+ return thumb;+ } catch (error) {+ await discardUnpublishedVideo({ jobId, outputPath });+ throw error;+ }+ });job.status = 'complete';- // The encode args already include -movflags +faststart, so no separate- // remux pass is needed here.- const thumb = await generateThumbnail(outputPath, jobId, { atSec: posterSec });-- // Push to existing video history with a timelineProjectId flag so the- // Media History page picks it up alongside generated clips.- const renderedNumFrames = Math.round(totalDuration * (fps || 24));- const meta = {- id: jobId,- prompt: `Timeline: ${project.name}`,- modelId: 'timeline',- seed: 0,- width: canonW,- height: canonH,- numFrames: renderedNumFrames,- fps: fps || 24,- filename,- thumbnail: thumb,- createdAt: new Date().toISOString(),- timelineProjectId: projectId,- };- // Serialized append through the single shared history tail so a concurrent- // download/render/timeline write can't clobber this entry.- await mutateVideoHistory((history) => { history.unshift(meta); return history; });console.log(`✅ Timeline rendered [${jobId.slice(0, 8)}]: ${filename}`);broadcastSse(job, { type: 'complete', result: { id: jobId, filename, thumbnail: thumb, path: `/data/videos/${filename}` } });projectRenders.delete(projectId);