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
fix: keep Music Video renders, publishing kits and composition documents whole across backups (#9982)
Adam Eivyb3dfb80c20ac
diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex 1eee895483..809c913507 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -80,7 +80,9 @@ Admission inventory (`withBackupAssetPublication`):| Pipeline audio stage rows: generated music, cue render and voice-over line render (`routes/pipeline/audio.js`) | Covered (#9982 partial): the row that first names the WAV takes the lease; the sidecar or synthesizer writes the WAV before it || Music-library upload attach: Music Designer upload, pipeline music upload and YouTube import (`routes/tracks.js`, `routes/pipeline/audio.js`, `trackYoutubeImport.js`) | Reference-only: the admitted library import copies the file first and the track or issue row commits after it || LoRA training and deployed LoRAs: trained-adapter registration, checkpoint promotion over the deployed adapter, the promoted-checkpoint preview copy, the progress row naming trainer-written samples and checkpoints, run deletion, and LoRA deletion from the LoRA manager or Media Models (`loraTraining/index.js`, `loras.js`) | Covered (#9982 partial): registration and promotion hold one lease from the adapter write through the run row and dataset flag; Civitai and Hugging Face installs admit the sidecar that first names the already-linked weights |-| Remaining durable owners, classified by domain in `backupAssetOwners.js` | Outstanding (#9982): sprites, Music Video renders and records, video generation, image generation tails, Writers Room drafts, code animation, peer and share imports, attachments and catalog media, mood boards, image-to-3D and rigging, archive and document imports |+| Music Video final and excerpt renders, publishing-kit builds and composition document versions (`musicVideo/render.js`, `musicVideo/excerptRender.js`, `musicVideo/publishKit.js`, `musicVideo/compositionDocument.js`) | Covered (#9982 partial): the encoder or import writes the files in place; the history entry and project row that first name them commit under one lease |+| Music Video excerpt deletion (`musicVideo/excerptService.js`) | Reference-only: the project row drops the excerpt before its unreferenced video and contact sheet are unlinked |+| Remaining durable owners, classified by domain in `backupAssetOwners.js` | Outstanding (#9982): sprites, Music Video performance repair, MIDI transcription and autonomous Suno song, video generation, image generation tails, Writers Room drafts, code animation, peer and share imports, attachments and catalog media, mood boards, image-to-3D and rigging, archive and document imports || Durable replacement/deletion owners not yet classified | Outstanding (#9982) || Snapshot consistency claim (`backupAssetOwners.js`, see below) | Covered (#9982 partial) || Database restore execution and backend-cutover acceptance (`backup.js`, `databasePreflight.js`) | Covered (#9983) |@@ -163,6 +165,17 @@ is written; the sidecar write takes the lease, so a snapshot can hold weightswithout their sidecar (they list with fallback metadata) but never a sidecarwithout its weights.+A Music Video render holds no lease while it encodes. Once the MP4 is on disk,+the final render's poster, its video-history entry and the project row naming+that entry commit under one lease; an excerpt's settling row (naming its MP4+and contact sheet) does the same. A publishing-kit build commits the kit row+naming its encodes, thumbnails and captions under a lease, then removes the+previous kit's files no project still names. A composition document version is+renamed into place before the row that selects it commits under a lease, and+pruning removes only version folders no row names. The in-flight+`renderPartialFilename` / excerpt `partialFilename` marks still name a file the+encoder is writing, as before; boot recovery clears them.+**Snapshot consistency claim.** `server/lib/backupAssetOwners.js` inventorieseach durable owner as `admitted`, `reference-only` or `outstanding`, and itstest fails when an `admitted` entry stops taking the lease or a module thatdiff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.jsindex 3dbcd8663a..47a1691c9b 100644--- a/server/lib/backupAssetOwners.js+++ b/server/lib/backupAssetOwners.js@@ -13,7 +13,10 @@* neither captured.* - `reference-only`: writes rows naming bytes that were already durable before* its trigger was published, and writes no bytes itself, so there is no gap- * for a cut to land in.+ * for a cut to land in. A deletion that commits the row that stops naming+ * its bytes before it removes them belongs here too: the dump that follows a+ * cut's file copy either sees no row, or sees one whose bytes were removed+ * only after the copy finished.* - `outstanding`: still changes bytes and rows outside admission.** A snapshot claims global file-and-row consistency only when nothing is@@ -106,6 +109,25 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([status: 'reference-only',modules: ['services/trackYoutubeImport.js'],},+ {+ // Final and excerpt renders, publishing-kit builds and composition document+ // versions: the encoder or import writes the MP4, kit files or version+ // folder in place, then the history entry and project row that first name+ // them commit under one lease (the final render's poster too).+ id: 'music-video-render-and-document-commits',+ status: 'admitted',+ modules: [+ 'services/musicVideo/render.js', 'services/musicVideo/excerptRender.js',+ 'services/musicVideo/publishKit.js', 'services/musicVideo/compositionDocument.js',+ ],+ },+ {+ // Excerpt deletion commits the project row without the excerpt, then+ // unlinks its video and contact sheet once no project names them.+ id: 'music-video-excerpt-deletion',+ status: 'reference-only',+ modules: ['services/musicVideo/excerptService.js'],+ },// Classified by a code sweep (#9982) but still outside admission. Each entry// names the modules whose file-plus-record workflows are not wrapped yet, so a// continuation can take one and move it up. Entries are per domain, not per@@ -122,14 +144,11 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([],},{- // Final and excerpt renders, publish kit, composition document versions,- // performance repair, MIDI transcription, excerpt deletion and the- // autonomous Suno song, where the MP4 or file is written in place.+ // Performance repair's boundary frame, MIDI transcription and the+ // autonomous Suno song, where the file is written in place.id: 'music-video-render-and-record-owners',status: 'outstanding',modules: [- 'services/musicVideo/render.js', 'services/musicVideo/excerptRender.js', 'services/musicVideo/excerptService.js',- 'services/musicVideo/publishKit.js', 'services/musicVideo/compositionDocument.js','services/musicVideo/performanceRepair.js', 'services/audioMidiTranscription.js','services/musicVideo/autonomousSuno.js', 'services/musicVideo/autonomousService.js', 'routes/musicVideo.js',],diff --git a/server/services/musicVideo/backupAdmission.test.js b/server/services/musicVideo/backupAdmission.test.jsnew file mode 100644index 0000000000..86240662c6--- /dev/null+++ b/server/services/musicVideo/backupAdmission.test.js@@ -0,0 +1,185 @@+/**+ * Music Video render and document commits against a backup cut (#9982), over+ * the real project store and real files. Each workflow writes its bytes in+ * place first (the encoder's MP4, the publishing kit's encodes, a composition+ * document's version folder), so the row that first names them must not commit+ * while a cut is open, and a cut must drain one already committing.+ */+import { afterAll, describe, expect, it, vi } from 'vitest';+import { existsSync } from 'node:fs';+import { mkdir, readdir, writeFile } from 'node:fs/promises';+import { join } from 'node:path';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';++vi.mock('../../lib/paths.js', async (importOriginal) => makePathsProxy(await importOriginal(), {+ dataRoot: () => lazyTempDataRoot('portos-mv-backup-admission-'),+}));+vi.mock('../../lib/databaseMaintenanceJournal.js', () => ({ assertDatabaseAdmission: () => {} }));+vi.mock('./productionReview.js', async (load) => ({ ...await load(), assertProductionApproval: vi.fn() }));+// The publishing kit's encodes and thumbnails are written as placeholders; the+// final render's poster is a fixed name.+vi.mock('../../lib/ffmpeg.js', async (importOriginal) => ({+ ...(await importOriginal()),+ generateThumbnail: vi.fn(async () => 'thumb.jpg'),+ findFfmpeg: vi.fn(async () => 'ffmpeg'),+ runFfmpegProcess: vi.fn(async ({ args }) => {+ await writeFile(args.at(-1), 'synthetic encode');+ return { ok: true };+ }),+}));+vi.mock('../instanceIdentity.js', () => ({ ensureInstanceId: vi.fn(async () => 'instance-test') }));+vi.mock('../videoGen/local.js', () => ({ loadHistory: vi.fn(async () => []), mutateVideoHistory: vi.fn(async () => {}) }));+vi.mock('./codeRender.js', async (importOriginal) => ({ ...(await importOriginal()), writeCodeProofSheet: vi.fn(async () => null) }));+vi.mock('./documentRender.js', async (importOriginal) => ({+ ...(await importOriginal()),+ encodeDocumentComposition: vi.fn(async ({ plan, outputPath }) => {+ await writeFile(outputPath, 'synthetic render');+ return { width: plan.width, height: plan.height, fps: 24, durationSec: plan.durationSec, startSec: 0, boundaryTimes: [0] };+ }),+}));++const { PATHS } = await import('../../lib/paths.js');+const projects = await import('./projects.js');+const { renderMusicVideo } = await import('./render.js');+const { startExcerptRender } = await import('./excerptRender.js');+const { importDocumentTemplate } = await import('./compositionDocument.js');+const { startPublishKitBuild } = await import('./publishKit.js');+const { encodeDocumentComposition } = await import('./documentRender.js');+const { runFfmpegProcess } = await import('../../lib/ffmpeg.js');+const { mutateVideoHistory } = await import('../videoGen/local.js');+const { saveHistory } = await import('../videoGen/history.js');+const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');++afterAll(() => cleanupTempDataRoots());++// Long enough for an unadmitted commit's file-backed project write to land, so+// a workflow still parked afterwards is parked on the cut.+const settleSeveral = () => new Promise(resolve => setTimeout(resolve, 100));+const deferred = () => {+ let resolve;+ const promise = new Promise(done => { resolve = done; });+ return { promise, resolve };+};++async function documentProject() {+ await mkdir(PATHS.music, { recursive: true });+ await writeFile(join(PATHS.music, 'song.wav'), Buffer.alloc(64));+ const created = await projects.createProject({ name: 'Example Song', uploadedAudioFilename: 'song.wav', composition: { mode: 'document' } });+ await projects.mutateProjectRecord(created.id, (current) => ({ project: { ...current, audioAnalysis: { durationSec: 12.5, beats: [], downbeats: [], sections: [] } } }));+ await importDocumentTemplate(created.id);+ return created.id;+}++describe('final render', () => {+ it('drains a render whose history entry is committing until the project row names it', async () => {+ const id = await documentProject();+ const held = deferred();+ const proceed = deferred();+ mutateVideoHistory.mockImplementationOnce(async () => { held.resolve(); await proceed.promise; });+ const { jobId } = await renderMusicVideo(id);+ await held.promise;+ let cutReady = false;+ const cut = acquireBackupSnapshotCut().then(release => { cutReady = true; return release; });+ try {+ await settleSeveral();+ expect(cutReady, 'cut acquired while the render was still committing').toBe(false);+ proceed.resolve();+ await cut;+ // Everything the cut dumps names bytes its copy already saw.+ expect((await projects.getProject(id)).renderHistoryId).toBe(jobId);+ } finally {+ proceed.resolve();+ (await cut)();+ }+ });++ it('files a render that finishes during a cut only after the cut is released', async () => {+ const id = await documentProject();+ mutateVideoHistory.mockClear();+ encodeDocumentComposition.mockClear();+ const release = await acquireBackupSnapshotCut();+ try {+ const { jobId } = await renderMusicVideo(id);+ await vi.waitFor(() => expect(encodeDocumentComposition).toHaveBeenCalledOnce());+ await settleSeveral();+ expect(mutateVideoHistory).not.toHaveBeenCalled();+ expect((await projects.getProject(id)).renderHistoryId ?? null).toBeNull();+ release();+ await vi.waitFor(async () => expect((await projects.getProject(id)).renderHistoryId).toBe(jobId));+ } finally {+ release();+ }+ });+});++describe('draft excerpt render', () => {+ it('keeps a finished excerpt rendering until the cut is released', async () => {+ const id = await documentProject();+ encodeDocumentComposition.mockClear();+ const release = await acquireBackupSnapshotCut();+ try {+ const { excerptId } = await startExcerptRender(id, { startSec: 1, endSec: 3 });+ await vi.waitFor(() => expect(encodeDocumentComposition).toHaveBeenCalledOnce());+ await settleSeveral();+ const pending = (await projects.getProject(id)).excerpts.find(e => e.id === excerptId);+ expect(pending).toMatchObject({ status: 'rendering', filename: null });+ release();+ await vi.waitFor(async () => {+ const excerpt = (await projects.getProject(id)).excerpts.find(e => e.id === excerptId);+ expect(excerpt.status).toBe('complete');+ expect(existsSync(join(PATHS.videos, excerpt.filename))).toBe(true);+ });+ } finally {+ release();+ }+ });+});++describe('composition document import', () => {+ it('writes the version folder but names it on the project only after the cut', async () => {+ const id = await documentProject();+ const before = (await projects.getProject(id)).composition.document.directory;+ const root = join(PATHS.data, 'music-video', id, 'composition');+ const release = await acquireBackupSnapshotCut();+ try {+ const importing = importDocumentTemplate(id);+ await vi.waitFor(async () => expect((await readdir(root)).filter(name => !name.startsWith('.'))).toHaveLength(2));+ await settleSeveral();+ expect((await projects.getProject(id)).composition.document.directory).toBe(before);+ release();+ const { document } = await importing;+ expect(document.directory).not.toBe(before);+ expect((await projects.getProject(id)).composition.document.directory).toBe(document.directory);+ } finally {+ release();+ }+ });+});++describe('publishing kit build', () => {+ it('names freshly encoded kit files on the project only after the cut', async () => {+ const id = await documentProject();+ await mkdir(PATHS.videos, { recursive: true });+ await writeFile(join(PATHS.videos, 'master-example.mp4'), 'synthetic master');+ await saveHistory([{ id: 'render-example', filename: 'master-example.mp4', durationSec: 12.5 }]);+ await projects.mutateProjectRecord(id, current => ({ project: { ...current, renderHistoryId: 'render-example' } }));+ runFfmpegProcess.mockClear();+ const release = await acquireBackupSnapshotCut();+ try {+ await startPublishKitBuild(id);+ // Thumbnails are the build's last ffmpeg step.+ await vi.waitFor(async () => expect((await readdir(PATHS.videoThumbnails)).some(name => name.endsWith('-thumb-6.jpg'))).toBe(true));+ await settleSeveral();+ const encoded = runFfmpegProcess.mock.calls.length;+ expect(encoded).toBeGreaterThan(6);+ expect((await projects.getProject(id)).publishKit?.exports).toBeUndefined();+ release();+ await vi.waitFor(async () => expect((await projects.getProject(id)).publishKit?.exports?.length).toBe(encoded - 6));+ for (const { filename } of (await projects.getProject(id)).publishKit.exports) {+ expect(existsSync(join(PATHS.videos, filename))).toBe(true);+ }+ } finally {+ release();+ }+ });+});diff --git a/server/services/musicVideo/compositionDocument.js b/server/services/musicVideo/compositionDocument.jsindex 489b30923f..da7aedf81c 100644--- a/server/services/musicVideo/compositionDocument.js+++ b/server/services/musicVideo/compositionDocument.js@@ -25,6 +25,7 @@ import { cp, lstat, mkdir, readdir, readFile, realpath, rename, rm, stat, writeFimport { dirname, extname, join, relative, resolve, sep } from 'path';import { fileURLToPath } from 'url';import { randomUUID } from 'crypto';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { ServerError } from '../../lib/errorHandler.js';import { PATHS } from '../../lib/fileUtils.js';import { isPathInsideDir } from '../../lib/pathSafety.js';@@ -176,13 +177,16 @@ async function storeVersionNow(projectId, files, source, { draft = false, verify};let outcome;try {- outcome = await mutateProjectRecord(projectId, (current) => {+ // The version folder is already in place; the row that first names it+ // commits under a backup lease (#9982). Pruning removes only folders no+ // row names any more, so it needs none.+ outcome = await withBackupAssetPublication(() => mutateProjectRecord(projectId, (current) => {verifyCurrent(current);if (current.mediaMode !== initial.mediaMode) throw refuse('Media mode changed during import', 'COMPOSITION_DRAFT_STALE', 409);const composition = normalizeComposition({ ...(current.composition || {}), ...(!draft ? { mode: 'document' } : {}) });const project = { ...current, composition: { ...composition, [draft ? 'documentDraft' : 'document']: document }, updatedAt: document.updatedAt };return { project };- });+ }));} catch (error) {await rm(finalDir, { recursive: true, force: true }).catch(() => {});throw error;diff --git a/server/services/musicVideo/excerptRender.js b/server/services/musicVideo/excerptRender.jsindex 0bcb9da5c7..dc540788e6 100644--- a/server/services/musicVideo/excerptRender.js+++ b/server/services/musicVideo/excerptRender.js@@ -18,6 +18,7 @@*/import { captureMusicVideoEvidence } from '../../lib/musicVideoDependencies.js';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { unlink } from 'fs/promises';import { join } from 'path';import { ensureDir, PATHS } from '../../lib/fileUtils.js';@@ -77,6 +78,13 @@ const unlinkUnder = (root, filename) => {return path ? unlink(path).catch(() => {}) : Promise.resolve();};+// The encoder wrote the excerpt and its contact sheet in place; the settling+// row that first names them commits under a backup lease (#9982), so a+// snapshot never dumps a row naming bytes its file copy missed.+const settleExcerptRecord = (projectId, excerptId, patch) => withBackupAssetPublication(() => mutateProjectRecord(projectId, (current) => ({+ project: settleRevisionRender(applyExcerptPatch(current, excerptId, { ...patch, partialFilename: null, renderingOn: null }), excerptId, patch),+})));+/*** Kick off a draft excerpt render. Returns `{ jobId, excerptId }`.* `revisionId` (#8987) links the render to an open selective revision in the@@ -175,9 +183,7 @@ async function launchSeekedExcerpt({ projectId, project: stored, startSec, endSeconst { signal } = job.overlayAbort;const finalize = async (patch) => {projectExcerptRenders.delete(projectId);- const persisted = await mutateProjectRecord(projectId, (current) => ({- project: settleRevisionRender(applyExcerptPatch(current, excerptId, { ...patch, partialFilename: null, renderingOn: null }), excerptId, patch),- })).then(() => true, (err) => {+ const persisted = await settleExcerptRecord(projectId, excerptId, patch).then(() => true, (err) => {console.error(`❌ Music-video ${renderer.label} excerpt [${jobId.slice(4, 12)}] project ${projectId.slice(0, 8)} status→${patch.status} write failed: ${err.message}`);return false;});@@ -322,9 +328,7 @@ export async function startExcerptRender(projectId, { startSec, endSec, aspect =// to refresh; boot recovery clears a record if that write also fails.const finalize = async (patch) => {projectExcerptRenders.delete(projectId);- const persisted = await mutateProjectRecord(projectId, (current) => ({- project: settleRevisionRender(applyExcerptPatch(current, excerptId, { ...patch, partialFilename: null, renderingOn: null }), excerptId, patch),- }))+ const persisted = await settleExcerptRecord(projectId, excerptId, patch).then(() => true, (err) => {console.error(`❌ Music-video excerpt render [${jobId.slice(4, 12)}] project ${projectId.slice(0, 8)} status→${patch.status} write failed: ${err.message}`);return false;diff --git a/server/services/musicVideo/publishKit.js b/server/services/musicVideo/publishKit.jsindex 55add3bc49..17d505319b 100644--- a/server/services/musicVideo/publishKit.js+++ b/server/services/musicVideo/publishKit.js@@ -15,6 +15,7 @@ import { randomUUID } from 'crypto';import { existsSync } from 'fs';import { unlink, writeFile } from 'fs/promises';import { join } from 'path';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { ServerError } from '../../lib/errorHandler.js';import { ensureDir, PATHS } from '../../lib/fileUtils.js';import { safeUnder, edgeFadeFilter } from '../../lib/ffmpeg.js';@@ -164,7 +165,9 @@ async function beginPublishKitBuild(projectId, jobId) {if (srt) { await writeFile(join(PATHS.videos, captionsFilename), srt); written.push(captionsFilename); }const previous = projectPublishKit(project);const staleFiles = [...(previous.exports || []).map((e) => e.filename), ...(previous.thumbnails || []), previous.captionsFilename].filter(Boolean);- await mutateProjectRecord(projectId, (current) => {+ // ffmpeg wrote the kit's files in place; the row that first names them+ // commits under a backup lease (#9982). Stale files go only after it.+ await withBackupAssetPublication(() => mutateProjectRecord(projectId, (current) => {const kit = projectPublishKit(current);return { project: { ...current, publishKit: {...kit,@@ -176,7 +179,7 @@ async function beginPublishKitBuild(projectId, jobId) {captionsFilename,chapters: buildChapters(current),} } };- });+ }));await releaseKitFiles(staleFiles, written);return written;};diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.jsindex cd63964bf1..a986a86619 100644--- a/server/services/musicVideo/render.js+++ b/server/services/musicVideo/render.js@@ -1,4 +1,5 @@import { maintenance } from '../../lib/maintenanceAdmission.js';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { assertMusicVideoMediaSelections } from '../../lib/musicVideoMediaPolicy.js';import { assertProductionApproval, productionReviewBasis } from './productionReview.js';import { musicVideoGradeFilter } from '../../lib/musicVideoGrade.js';@@ -719,12 +720,14 @@ async function renderSeekedMode(projectId, project, handOff, renderer, options =});console.log(`🎬 Rendering ${renderer.label} music video [${jobId.slice(0, 8)}]: project=${projectId.slice(0, 8)} frames=${Math.round(plan.durationSec * plan.fps)} footage=off`);const { signal } = job.overlayAbort;- const finish = async (patch) => {+ const writeSettled = (patch) => updateProject(projectId, settledRender(patch.status, { renderError: patch.status === 'failed' ? job.lastError?.slice(0, 2000) || 'Render failed' : null, ...patch.extra })).catch((err) => {+ maintenance.markCurrentUnsettled();+ console.error(`❌ Music-video ${renderer.label} render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→${patch.status} write failed: ${err.message}`);+ });+ // `written`: the success path already committed the row inside its backup lease.+ const finish = async (patch, { written = false } = {}) => {projectRenders.delete(projectId);- await updateProject(projectId, settledRender(patch.status, { renderError: patch.status === 'failed' ? job.lastError?.slice(0, 2000) || 'Render failed' : null, ...patch.extra })).catch((err) => {- maintenance.markCurrentUnsettled();- console.error(`❌ Music-video ${renderer.label} render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→${patch.status} write failed: ${err.message}`);- });+ if (!written) await writeSettled(patch);emitRenderSettled(projectId, job);if (options.productionRunId) musicVideoEvents.emit('document-render', { projectId, runId: options.productionRunId, attemptId: options.productionRenderAttemptId, jobId, status: patch.status === 'complete' ? 'completed' : 'failed', error: job.lastError || null });closeJobAfterDelay(jobs, jobId);@@ -750,22 +753,29 @@ async function renderSeekedMode(projectId, project, handOff, renderer, options =console.warn(`⚠️ Music-video ${renderer.label} proof sheet failed [${jobId.slice(0, 8)}]: ${err.message}`);}const atSec = typeof project.composition?.posterSec === 'number' ? project.composition.posterSec : (encoded.boundaryTimes[0] || 0);- const thumb = await generateThumbnail(outputPath, jobId, { atSec });- await appendToVideoHistory({- id: jobId,- prompt: `Music Video: ${project.name}`,- modelId: renderer.modelId,- seed: 0,- width: encoded.width,- height: encoded.height,- numFrames: Math.round(encoded.durationSec * encoded.fps),- fps: encoded.fps,- filename,- thumbnail: thumb,- createdAt: new Date().toISOString(),- musicVideoProjectId: projectId,+ const completed = { status: 'complete', extra: { renderHistoryId: jobId, renderDependencies: captureMusicVideoEvidence(project) } };+ // The encoder wrote the MP4 in place; the poster, the history entry naming+ // it and the project row naming that entry publish under one lease (#9982).+ const thumb = await withBackupAssetPublication(async () => {+ const poster = await generateThumbnail(outputPath, jobId, { atSec });+ await appendToVideoHistory({+ id: jobId,+ prompt: `Music Video: ${project.name}`,+ modelId: renderer.modelId,+ seed: 0,+ width: encoded.width,+ height: encoded.height,+ numFrames: Math.round(encoded.durationSec * encoded.fps),+ fps: encoded.fps,+ filename,+ thumbnail: poster,+ createdAt: new Date().toISOString(),+ musicVideoProjectId: projectId,+ });+ await writeSettled(completed);+ return poster;});- await finish({ status: 'complete', extra: { renderHistoryId: jobId, renderDependencies: captureMusicVideoEvidence(project) } });+ await finish(completed, { written: true });console.log(`✅ ${renderer.label[0].toUpperCase()}${renderer.label.slice(1)} music video rendered [${jobId.slice(0, 8)}]: ${filename}`);broadcastSse(job, { type: 'complete', result: { id: jobId, filename, thumbnail: thumb, path: `/data/videos/${filename}`, proof: proof ? `/data/video-thumbnails/${proof}` : null } });}).catch(async (err) => {@@ -965,25 +975,29 @@ async function renderAdmittedMusicVideo(projectId, options, permit) {const posterSec = project.composition?.posterSec;const atSec = typeof posterSec === 'number' && posterSec < totalDuration ? posterSec: section ? (section.startSec + Math.min(section.endSec, totalDuration)) / 2 : undefined;- const thumb = await generateThumbnail(outputPath, jobId, { atSec });- const meta = {- id: jobId,- prompt: `Music Video: ${project.name}`,- modelId: 'music-video',- seed: 0,- width: canonW,- height: canonH,- numFrames: Math.round(totalDuration * (fps || 24)),- fps: fps || 24,- filename,- thumbnail: thumb,- createdAt: new Date().toISOString(),- musicVideoProjectId: projectId,- };- await appendToVideoHistory(meta);- await updateProject(projectId, settledRender('complete', { renderHistoryId: jobId, renderDependencies: captureMusicVideoEvidence(project) })).catch((updateErr) => {- maintenance.markCurrentUnsettled();- console.error(`❌ Music-video render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→complete write failed: ${updateErr.message}`);+ // ffmpeg wrote the MP4 in place; the poster, the history entry naming+ // it and the project row naming that entry publish under one lease (#9982).+ const thumb = await withBackupAssetPublication(async () => {+ const poster = await generateThumbnail(outputPath, jobId, { atSec });+ await appendToVideoHistory({+ id: jobId,+ prompt: `Music Video: ${project.name}`,+ modelId: 'music-video',+ seed: 0,+ width: canonW,+ height: canonH,+ numFrames: Math.round(totalDuration * (fps || 24)),+ fps: fps || 24,+ filename,+ thumbnail: poster,+ createdAt: new Date().toISOString(),+ musicVideoProjectId: projectId,+ });+ await updateProject(projectId, settledRender('complete', { renderHistoryId: jobId, renderDependencies: captureMusicVideoEvidence(project) })).catch((updateErr) => {+ maintenance.markCurrentUnsettled();+ console.error(`❌ Music-video render [${jobId.slice(0, 8)}] project ${projectId.slice(0, 8)} status→complete write failed: ${updateErr.message}`);+ });+ return poster;});emitRenderSettled(projectId, job);console.log(`✅ Music video rendered [${jobId.slice(0, 8)}]: ${filename}`);