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 library video publications to backup cuts (#9982) (#10295)

[._.]/1a7aae95cf98
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 8ec284b9f6..84b8ac797d 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -74,6 +74,7 @@ Admission inventory (`withBackupAssetPublication`):
| Direct gallery upload, image prompt/visibility sidecar replacement, and image deletion (`imageGen/local.js`) | Covered as one file/sidecar/index workflow (#9982 partial) |
| Gallery image deletion's universe canon purge (`galleryImageDeletion.js`) and character reference sheet deletion (`universeCharacterSheet.js`) | Covered from file removal through the universe pointer purge (#9982 partial) |
| Video-history deletion, including downloaded-video deletion (`videoGen/historyOps.js`) | Covered through file/history/index removal (#9982 partial) |
+| Gallery video upload, download finalization and poster edits (`videoUpload.js`, `videoDownload.js`, `videoGen/poster.js`) | Covered (#9982 partial): uploads lease byte installation through history and rollback; downloads lease poster creation through history and rollback after yt-dlp finishes; poster edits lease creation, history and cleanup |
| LoRA dataset uploads, gallery imports, reference-sheet crops, generated completion/recovery copies, image/dataset deletion, and queued record edits (`loraDatasets.js`, `loraDatasetGenerate.js`) | Covered as complete file/record workflows (#9982 partial) |
| Voice Studio audition and character assignment (`voice/studio.js`) | Covered from source-file write/copy through profile-row commit and failed-write cleanup (#9982 partial) |
| Music Video development artifact import/generated save and vocal-stem attachment (`musicVideo/devArtifactService.js`, `musicVideo/vocalStem.js`) | Covered from final file copy/write through project-record commit and failed-write cleanup (#9982 partial) |
@@ -98,7 +99,7 @@ Admission inventory (`withBackupAssetPublication`):
| ChatGPT archive import and import-memory deletion (`chatgptImport.js`, `brain.js`; the ZIP's asset extraction in `chatgptZipImport.js`) | Covered (#9982 partial): assets are extracted outside admission and named only by the memory row; each conversation's archived transcript and that row commit under one lease, and deleting an import memory drops the record and unlinks its transcript and unreferenced assets under one lease |
| 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 |
-| Remaining durable owners, classified by domain in `backupAssetOwners.js` | Outstanding (#9982): video generation, image generation tails |
+| Remaining durable owners, classified by domain in `backupAssetOwners.js` | Outstanding (#9982): video generation, image generation tails, derived media-index refresh |
| 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) |
@@ -219,6 +220,22 @@ repeat, so that write takes the lease too. Removing a board item or a board
removes no bytes. A row that fails after its file landed leaves an unreferenced
file, as before.
+Gallery video uploads hold admission from the first byte installation through
+their thumbnail and history entry; failed history writes remove both outputs
+before releasing admission. The yt-dlp producer downloads fresh, unreferenced
+files outside admission, then the poster and history commit take one lease,
+including rollback. Failed or canceled producers remove their unreferenced
+fragments through the existing download core. Poster edits take admission before
+the shared history write tail and retain it through poster creation, history
+replacement, old-poster cleanup and failed-commit cleanup. Every new poster uses
+a fresh basename; temporary sharing copies stay outside this durable workflow.
+Upload and download completion notifications run after the durable commit, so
+a throwing listener cannot remove files that committed history already names.
+These leases do not repair dangling references or stale derived index metadata.
+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.
+
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 6f13cb5fe6..bfb9394b9b 100644
--- a/server/lib/backupAssetOwners.js
+++ b/server/lib/backupAssetOwners.js
@@ -286,19 +286,37 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([
// 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
// function: a module listed here may also hold already-admitted workflows.
+ {
+ // Gallery uploads hold one lease from byte installation through their
+ // history entry and rollback. Downloads run yt-dlp outside admission, then
+ // lease the poster and history commit with rollback. Poster edits acquire
+ // before the history tail and keep creation, commit and cleanup together.
+ id: 'video-library-import-and-poster-publication',
+ status: 'admitted',
+ modules: ['services/videoUpload.js', 'services/videoDownload.js', 'services/videoGen/poster.js'],
+ },
{
// Local, cloud and federated finalize, derived clips (stitch, upscale,
- // timeline, HTML composition), poster replacement, upload and download.
+ // timeline, HTML composition). Library imports and poster edits are above.
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/stitchVideos.js', 'services/videoGen/upscaleVideo.js', 'services/videoGen/upscaleJob.js',
- 'services/videoGen/poster.js', 'services/videoTimeline/local.js', 'services/htmlComposition/index.js',
- 'services/videoUpload.js', 'services/videoDownload.js',
+ 'services/videoTimeline/local.js', 'services/htmlComposition/index.js',
],
},
+ {
+ // Async completion hooks and full reconciliation read file-backed media
+ // metadata before their derived Postgres writes, outside workflow admission.
+ // Poster edits also leave old thumbnail metadata in this derived mirror.
+ // Classify and verify the mirror's restore semantics in the final sweep;
+ // admitting authoritative history alone does not settle these DB pointers.
+ id: 'media-asset-index-refresh',
+ status: 'outstanding',
+ modules: ['services/mediaAssetIndex/index.js', 'services/mediaAssetIndex/db.js'],
+ },
{
// The post-exit tails of the generation lanes (upscale, sidecar, auto-clean),
// variants and sketch pairs. `imageGen/local.js` takes the lease only for
diff --git a/server/services/videoDownload.js b/server/services/videoDownload.js
index 322a32d033..ddc3c39753 100644
--- a/server/services/videoDownload.js
+++ b/server/services/videoDownload.js
@@ -25,7 +25,8 @@
import { join } from 'path';
import { randomUUID } from 'crypto';
import { ServerError } from '../lib/errorHandler.js';
-import { shortId, PATHS } from '../lib/fileUtils.js';
+import { shortId, PATHS, unlinkGuarded } from '../lib/fileUtils.js';
+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';
import { findFfmpeg, generateThumbnail, probeVideoDuration } from '../lib/ffmpeg.js';
import { findYtDlp } from '../lib/ytdlp.js';
import { killWithEscalation } from '../lib/killWithEscalation.js';
@@ -157,8 +158,9 @@ export async function downloadVideoIntoLibrary({
maxDurationSec = VIDEO_DOWNLOAD_MAX_DURATION_SEC, onProgress, registerProcess,
}) {
const jobId = id || randomUUID();
+ let result;
try {
- const result = await downloadVideoToDir({
+ result = await downloadVideoToDir({
url,
ytDlp,
ffmpeg,
@@ -169,33 +171,43 @@ export async function downloadVideoIntoLibrary({
onProgress,
registerProcess,
});
- if (result.outcome !== 'complete') return result;
-
- const { filename, title } = result;
- const outPath = join(PATHS.videos, filename);
- onProgress?.({ percent: 100, stage: 'finalizing' });
- const [thumbnail, durationSec] = await Promise.all([
- generateThumbnail(outPath, jobId),
- probeVideoDuration(outPath).catch(() => null),
- ]);
-
- // Derived, not a generation: a `source: 'download'` video-history entry so
- // the existing videoToRow / onVideoCompleted media-index path and the
- // gallery pick it up unmodified. Serialized read-modify-write so two
- // near-simultaneous downloads can't clobber each other's entry.
- const entry = buildDownloadHistoryEntry({ jobId, filename, thumbnail, durationSec, title, sourceUrl: url });
- await mutateVideoHistory((history) => { history.unshift(entry); return history; });
-
- // Let the live media-asset index hook index this immediately (it loads
- // history by generationId and upserts one row). Reconcile is the backstop.
- videoGenEvents.emit('completed', { generationId: jobId, filename, path: `/data/videos/${filename}`, thumbnail });
- return { outcome: 'complete', entry };
} catch (err) {
- // A throw between the download and the history write would otherwise orphan
- // a multi-GB file in data/videos with nothing pointing at it.
await cleanupDownloadFiles(jobId);
throw err;
}
+ if (result.outcome !== 'complete') return result;
+ // The long producer writes fresh, unreferenced bytes outside admission.
+ // Its poster and the history commit (including rollback) share one lease.
+ const entry = await withBackupAssetPublication(async () => {
+ try {
+ const { filename, title } = result;
+ const outPath = join(PATHS.videos, filename);
+ onProgress?.({ percent: 100, stage: 'finalizing' });
+ const [thumbnail, durationSec] = await Promise.all([
+ generateThumbnail(outPath, jobId),
+ probeVideoDuration(outPath).catch(() => null),
+ ]);
+ if (!thumbnail) await unlinkGuarded(join(PATHS.videoThumbnails, `${jobId}.jpg`)).catch(() => {});
+
+ // Derived, not a generation: a `source: 'download'` video-history entry so
+ // the existing videoToRow / onVideoCompleted media-index path and the
+ // gallery pick it up unmodified. Serialized read-modify-write so two
+ // near-simultaneous downloads can't clobber each other's entry.
+ const entry = buildDownloadHistoryEntry({ jobId, filename, thumbnail, durationSec, title, sourceUrl: url });
+ await mutateVideoHistory((history) => { history.unshift(entry); return history; });
+
+ return entry;
+ } catch (err) {
+ // A throw between the download and the history write would otherwise orphan
+ // a multi-GB file in data/videos with nothing pointing at it.
+ await cleanupDownloadFiles(jobId);
+ await unlinkGuarded(join(PATHS.videoThumbnails, `${jobId}.jpg`)).catch(() => {});
+ throw err;
+ }
+ });
+ // Notify only after publication; a listener failure cannot remove committed bytes.
+ videoGenEvents.emit('completed', { generationId: jobId, filename: entry.filename, path: `/data/videos/${entry.filename}`, thumbnail: entry.thumbnail });
+ return { outcome: 'complete', entry };
}
/**
diff --git a/server/services/videoGen/poster.js b/server/services/videoGen/poster.js
index 923000b65a..aa010fccd0 100644
--- a/server/services/videoGen/poster.js
+++ b/server/services/videoGen/poster.js
@@ -7,6 +7,7 @@ import { PATHS, unlinkGuarded } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { safeUnder, generateThumbnail, probeVideoDuration, probeVideoStreamInfo, findFfmpeg, runFfmpegProcess } from '../../lib/ffmpeg.js';
import { getHistoryItem, mutateVideoHistory } from './history.js';
+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
function sourcePath(item) {
const path = item && safeUnder(PATHS.videos, item.filename);
@@ -15,36 +16,42 @@ function sourcePath(item) {
}
export async function updateVideoPoster(id, atSec) {
- let result;
- let generated;
- let previous;
- try {
- await mutateVideoHistory(async history => {
- const item = history.find(item => item.id === id);
- const path = sourcePath(item);
- let posterSec;
- if (atSec !== null) {
- const [duration, stream] = await Promise.all([probeVideoDuration(path), probeVideoStreamInfo(path)]);
- if (!duration) throw new ServerError('Could not read video duration', { status: 422 });
- posterSec = Math.max(0, Math.min(atSec, duration - (stream.fps > 0 ? 1 / stream.fps : Math.min(duration, 0.001))));
- }
- // A new basename prevents browser caching and leaves the old poster intact on failure.
- generated = await generateThumbnail(path, `${id}-poster-${randomUUID()}`, { atSec: posterSec });
- if (!generated) throw new ServerError('Could not generate poster', { status: 422 });
- previous = item.thumbnail;
- item.thumbnail = generated;
- if (posterSec === undefined) delete item.posterSec;
- else item.posterSec = posterSec;
- result = { id, thumbnail: generated, posterSec: posterSec ?? null };
- return history;
- });
- } catch (error) {
- if (generated) await unlinkGuarded(join(PATHS.videoThumbnails, generated)).catch(() => {});
- throw error;
- }
- const old = previous && safeUnder(PATHS.videoThumbnails, previous);
- if (old) await unlinkGuarded(old).catch(() => {});
- return result;
+ // Acquire before the history tail: poster creation, commit and cleanup must
+ // drain together, including a failed commit that removes its new poster.
+ return withBackupAssetPublication(async () => {
+ let result;
+ let generated;
+ let previous;
+ try {
+ await mutateVideoHistory(async history => {
+ const item = history.find(item => item.id === id);
+ const path = sourcePath(item);
+ let posterSec;
+ if (atSec !== null) {
+ const [duration, stream] = await Promise.all([probeVideoDuration(path), probeVideoStreamInfo(path)]);
+ if (!duration) throw new ServerError('Could not read video duration', { status: 422 });
+ posterSec = Math.max(0, Math.min(atSec, duration - (stream.fps > 0 ? 1 / stream.fps : Math.min(duration, 0.001))));
+ }
+ // A new basename prevents browser caching and leaves the old poster intact on failure.
+ const posterId = `${id}-poster-${randomUUID()}`;
+ generated = `${posterId}.jpg`;
+ const thumbnail = await generateThumbnail(path, posterId, { atSec: posterSec });
+ if (!thumbnail) throw new ServerError('Could not generate poster', { status: 422 });
+ previous = item.thumbnail;
+ item.thumbnail = generated;
+ if (posterSec === undefined) delete item.posterSec;
+ else item.posterSec = posterSec;
+ result = { id, thumbnail: generated, posterSec: posterSec ?? null };
+ return history;
+ });
+ } catch (error) {
+ if (generated) await unlinkGuarded(join(PATHS.videoThumbnails, generated)).catch(() => {});
+ throw error;
+ }
+ const old = previous && safeUnder(PATHS.videoThumbnails, previous);
+ if (old) await unlinkGuarded(old).catch(() => {});
+ return result;
+ });
}
export async function createSharingCopy(id, { signal } = {}) {
diff --git a/server/services/videoLibrary.backupAdmission.test.js b/server/services/videoLibrary.backupAdmission.test.js
new file mode 100644
index 0000000000..4b3e1fd3a2
--- /dev/null
+++ b/server/services/videoLibrary.backupAdmission.test.js
@@ -0,0 +1,371 @@
+/**
+ * Library publications against a file-copy cut (#9982). Producers are
+ * synthetic, but bytes, the serialized history store and the boundary are real.
+ * Each held-cut case also bypasses admission as a negative control: its
+ * copied history then names an output missing from the already-copied assets.
+ */
+import { afterAll, afterEach, beforeEach, describe, expect, it as vitestIt, vi } from 'vitest';
+import { existsSync } from 'node:fs';
+import { cp, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
+import { basename, join } from 'node:path';
+import {
+ cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy, ownTestBodies,
+} from '../lib/mockPathsDataRoot.js';
+
+const state = vi.hoisted(() => ({
+ admission: null, bypass: false, historyGate: null, unlinkGate: null,
+ failHistory: false, thumbnailFailure: null, copyFailure: false,
+ producerExit: null, producerGate: null,
+}));
+
+vi.mock('../lib/fileUtils.js', async importOriginal => {
+ const actual = await importOriginal();
+ return makePathsProxy(actual, {
+ dataRoot: () => lazyTempDataRoot('portos-video-library-admission-'),
+ overrides: {
+ atomicWrite: async (path, value) => {
+ if (basename(path) === 'video-history.json') {
+ const gate = state.historyGate;
+ gate?.entered.resolve();
+ if (gate) await gate.finish.promise;
+ if (state.failHistory) throw new Error('history commit failed');
+ }
+ return actual.atomicWrite(path, value);
+ },
+ copyFileGuarded: async (source, dest) => {
+ await actual.copyFileGuarded(source, dest);
+ if (state.copyFailure) throw new Error('copy failed after staging');
+ },
+ unlinkGuarded: async path => {
+ const gate = state.unlinkGate;
+ if (gate?.matches(path)) {
+ gate.entered.resolve();
+ await gate.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', async importOriginal => ({
+ ...(await importOriginal()),
+ generateThumbnail: vi.fn(async (_path, id) => {
+ const { PATHS } = await import('../lib/fileUtils.js');
+ await mkdir(PATHS.videoThumbnails, { recursive: true });
+ await writeFile(join(PATHS.videoThumbnails, `${id}.jpg`), `poster:${id}`);
+ if (state.thumbnailFailure === 'throw') throw new Error('poster render failed');
+ return state.thumbnailFailure === 'null' ? null : `${id}.jpg`;
+ }),
+ probeVideoDuration: vi.fn(async () => 2),
+ probeVideoStreamInfo: vi.fn(async () => ({ fps: 10 })),
+}));
+vi.mock('./videoGen/local.js', () => ({ deleteHistoryItem: vi.fn() }));
+// Exercise the real download core's discovery and fragment cleanup without a
+// subprocess, network, provider or credentials.
+vi.mock('./ytdlpRun.js', () => ({
+ ytdlpMarkerArgs: () => [], describeYtDlpFailure: () => 'download failed',
+ runYtDlp: vi.fn(async ({ args }) => {
+ const path = args[args.indexOf('-o') + 1].replace('%(ext)s', 'mp4');
+ await writeFile(path, 'download bytes');
+ const exit = state.producerExit || { code: 0, title: 'Fixture clip' };
+ if (exit.canceled || exit.code !== 0) await writeFile(`${path}.part`, 'partial bytes');
+ state.producerGate?.entered.resolve();
+ if (state.producerGate) await state.producerGate.finish.promise;
+ return exit;
+ }),
+}));
+
+const { PATHS } = await import('../lib/fileUtils.js');
+const { acquireBackupSnapshotCut } = await import('../lib/backupSnapshotBoundary.js');
+const { saveUploadedGalleryVideoBuffer, saveUploadedGalleryVideoFile } = await import('./videoUpload.js');
+const { downloadVideoIntoLibrary } = await import('./videoDownload.js');
+const { updateVideoPoster } = await import('./videoGen/poster.js');
+const { loadHistory, mutateVideoHistory, saveHistory } = await import('./videoGen/history.js');
+const { videoGenEvents } = await import('./videoGen/events.js');
+const { generateThumbnail } = await import('../lib/ffmpeg.js');
+const owned = ownTestBodies(vitestIt);
+const it = owned.it;
+
+function deferred() {
+ let resolve;
+ const promise = new Promise(done => { resolve = done; });
+ return { promise, resolve };
+}
+const pause = () => ({ entered: deferred(), finish: deferred() });
+const checkpoint = () => new Promise(resolve => setImmediate(resolve));
+const uploadBytes = Buffer.concat([Buffer.from([0, 0, 0, 24]), Buffer.from('ftypisomfixture')]);
+const download = () => downloadVideoIntoLibrary({ url: 'https://example.com/fixture', ytDlp: 'unused', ffmpeg: 'unused', id: 'fixture-download' });
+
+beforeEach(async () => {
+ await owned.drain();
+ Object.assign(state, {
+ admission: null, bypass: false, historyGate: null, unlinkGate: null,
+ failHistory: false, thumbnailFailure: null, copyFailure: false,
+ producerExit: null, producerGate: null,
+ });
+ await rm(PATHS.data, { recursive: true, force: true });
+ await mkdir(PATHS.videos, { recursive: true });
+ await mkdir(PATHS.videoThumbnails, { recursive: true });
+ await saveHistory([]);
+ vi.mocked(generateThumbnail).mockClear();
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+});
+afterEach(async () => {
+ state.historyGate?.finish.resolve();
+ state.unlinkGate?.finish.resolve();
+ state.producerGate?.finish.resolve();
+ await owned.drain();
+ videoGenEvents.removeAllListeners('completed');
+});
+afterAll(async () => {
+ try { await owned.drain(); } finally { cleanupTempDataRoots(); }
+});
+
+async function prepare(kind) {
+ if (kind === 'file upload') {
+ const path = join(PATHS.data, 'input.mp4');
+ await writeFile(path, uploadBytes);
+ return () => saveUploadedGalleryVideoFile(path, 'fixture.mp4');
+ }
+ if (kind === 'poster') {
+ await writeFile(join(PATHS.videos, 'existing.mp4'), 'existing video');
+ await writeFile(join(PATHS.videoThumbnails, 'old.jpg'), 'old poster');
+ await saveHistory([{ id: 'existing', filename: 'existing.mp4', thumbnail: 'old.jpg', posterSec: 0.5 }]);
+ return () => updateVideoPoster('existing', 1);
+ }
+ return kind === 'download' ? download : () => saveUploadedGalleryVideoBuffer(uploadBytes, 'fixture.mp4');
+}
+
+async function copyAssets() {
+ const root = join(PATHS.data, 'copied');
+ await cp(PATHS.videos, join(root, 'videos'), { recursive: true });
+ await cp(PATHS.videoThumbnails, join(root, 'posters'), { recursive: true });
+ return root;
+}
+// History is itself file-backed snapshot data, not a simulated Postgres dump.
+// Separate these copy points so publication can land between assets and history.
+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'));
+}
+async function copyFiles() {
+ const root = await copyAssets();
+ await copyHistory(root);
+ return root;
+}
+function missingReferences(rows, root) {
+ return rows.flatMap(row => [
+ !existsSync(join(root, 'videos', row.filename)) ? row.filename : null,
+ row.thumbnail && !existsSync(join(root, 'posters', row.thumbnail)) ? row.thumbnail : null,
+ ].filter(Boolean));
+}
+
+describe('video library backup publication', () => {
+ for (const kind of ['buffer upload', 'file upload', 'download', 'poster']) {
+ it(`${kind} waits out an asset/history copy; bypassing its lease leaves copied history naming a missing asset`, async () => {
+ const run = await prepare(kind);
+ const release = await acquireBackupSnapshotCut();
+ const copied = await copyAssets();
+ state.admission = deferred();
+ let pending;
+ try {
+ pending = run();
+ await state.admission.promise;
+ await checkpoint();
+ const snapshotHistory = await copyHistory(copied);
+ expect(snapshotHistory).toEqual(await loadHistory());
+ expect(missingReferences(snapshotHistory, copied)).toEqual([]);
+ expect(generateThumbnail).not.toHaveBeenCalled();
+ } finally { release(); }
+ await pending;
+ expect(await loadHistory()).toHaveLength(1);
+ // The negative control publishes between the asset and history copies.
+ await rm(join(PATHS.data, 'copied'), { recursive: true, force: true });
+ for (const dir of [PATHS.videos, PATHS.videoThumbnails]) {
+ await rm(dir, { recursive: true, force: true });
+ await mkdir(dir, { recursive: true });
+ }
+ await saveHistory([]);
+ const controlRun = await prepare(kind);
+ const releaseControl = await acquireBackupSnapshotCut();
+ const controlCopy = await copyAssets();
+ state.bypass = true;
+ try {
+ await controlRun();
+ const controlHistory = await copyHistory(controlCopy);
+ expect(missingReferences(controlHistory, controlCopy).length).toBeGreaterThan(0);
+ } finally {
+ state.bypass = false;
+ releaseControl();
+ }
+ });
+
+ it(`${kind} drains through the real serialized history commit before files and rows are captured`, async () => {
+ const run = await prepare(kind);
+ const gate = state.historyGate = pause();
+ const pending = run();
+ await gate.entered.promise;
+ let cutReady = false;
+ const cut = acquireBackupSnapshotCut().then(release => { cutReady = true; return release; });
+ let release;
+ try {
+ await checkpoint();
+ expect(cutReady).toBe(false);
+ gate.finish.resolve();
+ await pending;
+ release = await cut;
+ const copied = await copyFiles();
+ const snapshotHistory = JSON.parse(await readFile(join(copied, 'history.json'), 'utf8'));
+ expect(missingReferences(snapshotHistory, copied)).toEqual([]);
+ expect(snapshotHistory).toEqual(await loadHistory());
+ for (const row of snapshotHistory) {
+ expect(await readFile(join(copied, 'videos', row.filename))).toEqual(await readFile(join(PATHS.videos, row.filename)));
+ expect(await readFile(join(copied, 'posters', row.thumbnail))).toEqual(await readFile(join(PATHS.videoThumbnails, row.thumbnail)));
+ }
+ if (kind === 'poster') expect(existsSync(join(copied, 'posters', 'old.jpg'))).toBe(false);
+ } finally {
+ gate.finish.resolve();
+ await pending.catch(() => {});
+ (release || await cut)();
+ }
+ });
+
+ it(`${kind} keeps failed-commit rollback inside admission and preserves prior history`, async () => {
+ const run = await prepare(kind);
+ const before = await loadHistory();
+ state.failHistory = true;
+ const gate = state.unlinkGate = { ...pause(), matches: path => kind === 'poster'
+ ? basename(path).startsWith('existing-poster-') : path.startsWith(PATHS.videos) && !path.endsWith('.tmp') };
+ // Download rollback uses the real core's direct unlink, so gate its poster
+ // cleanup, which runs after the produced fragments have been removed.
+ if (kind === 'download') gate.matches = path => path === join(PATHS.videoThumbnails, 'fixture-download.jpg');
+ const pending = run().then(() => null, error => error);
+ await gate.entered.promise;
+ let cutReady = false;
+ const cut = acquireBackupSnapshotCut().then(release => { cutReady = true; return release; });
+ let release;
+ try {
+ await checkpoint();
+ expect(cutReady).toBe(false);
+ gate.finish.resolve();
+ expect(await pending).toMatchObject({ message: 'history commit failed' });
+ release = await cut;
+ expect(await loadHistory()).toEqual(before);
+ expect(await readdir(PATHS.videos)).toEqual(kind === 'poster' ? ['existing.mp4'] : []);
+ expect(await readdir(PATHS.videoThumbnails)).toEqual(kind === 'poster' ? ['old.jpg'] : []);
+ expect(missingReferences(await loadHistory(), await copyFiles())).toEqual([]);
+ } finally {
+ gate.finish.resolve();
+ await pending;
+ (release || await cut)();
+ }
+ });
+ }
+
+ it('takes poster admission before waiting for the shared history tail', async () => {
+ const run = await prepare('poster');
+ const gate = pause();
+ const blocker = mutateVideoHistory(async history => { gate.entered.resolve(); await gate.finish.promise; return history; });
+ await gate.entered.promise;
+ state.admission = deferred();
+ const pending = run();
+ await state.admission.promise;
+ let cutReady = false;
+ const cut = acquireBackupSnapshotCut().then(release => { cutReady = true; return release; });
+ try { await checkpoint(); expect(cutReady).toBe(false); }
+ finally {
+ gate.finish.resolve();
+ await blocker;
+ await pending;
+ (await cut)();
+ }
+ });
+
+ for (const kind of ['buffer upload', 'download']) {
+ it(`${kind} retains the committed pair if completion notification dispatch throws`, async () => {
+ const run = await prepare(kind);
+ // Ordinary listener errors are fault-isolated by the real emitter. Inject
+ // a dispatch failure itself to prove the publication catch cannot undo
+ // a pair after the authoritative history commit has already succeeded.
+ vi.spyOn(videoGenEvents, 'emit').mockImplementationOnce(() => { throw new Error('notification failed'); });
+ await expect(run()).rejects.toThrow('notification failed');
+ const release = await acquireBackupSnapshotCut();
+ try {
+ expect(await loadHistory()).toHaveLength(1);
+ expect(missingReferences(await loadHistory(), await copyFiles())).toEqual([]);
+ } finally { release(); }
+ });
+ }
+
+ for (const exit of [{ canceled: true, code: null }, { code: 1, reason: 'fixture failure' }]) {
+ it(`cleans ${exit.canceled ? 'canceled' : 'failed'} download fragments outside admission without publishing history`, async () => {
+ state.producerExit = exit;
+ state.producerGate = pause();
+ const release = await acquireBackupSnapshotCut();
+ try {
+ const pending = download();
+ await state.producerGate.entered.promise;
+ expect(await readdir(PATHS.videos)).toHaveLength(2);
+ state.producerGate.finish.resolve();
+ expect(await pending).toMatchObject({ outcome: exit.canceled ? 'canceled' : 'failed' });
+ expect(await readdir(PATHS.videos)).toEqual([]);
+ expect(await readdir(PATHS.videoThumbnails)).toEqual([]);
+ expect(await loadHistory()).toEqual([]);
+ } finally { state.producerGate.finish.resolve(); release(); }
+ });
+ }
+
+ it('removes a failed streamed upload staging file and leaves its source intact', async () => {
+ const run = await prepare('file upload');
+ state.copyFailure = true;
+ await expect(run()).rejects.toThrow('copy failed after staging');
+ expect(await readdir(PATHS.videos)).toEqual([]);
+ expect(await readFile(join(PATHS.data, 'input.mp4'))).toEqual(uploadBytes);
+ expect(await loadHistory()).toEqual([]);
+ });
+
+ for (const failure of ['throw', 'null']) {
+ it(`keeps thumbnail-less upload compatibility (${failure}) and removes a partial poster`, async () => {
+ state.thumbnailFailure = failure;
+ const entry = await saveUploadedGalleryVideoBuffer(uploadBytes);
+ expect(entry.thumbnail).toBeNull();
+ expect(await readdir(PATHS.videoThumbnails)).toEqual([]);
+ expect(await readFile(join(PATHS.videos, entry.filename))).toEqual(uploadBytes);
+ });
+
+ it(`removes a partially rendered poster (${failure}) and preserves the selected old poster`, async () => {
+ const run = await prepare('poster');
+ state.thumbnailFailure = failure;
+ await expect(run()).rejects.toThrow(/poster render failed|Could not generate poster/);
+ expect(await readdir(PATHS.videoThumbnails)).toEqual(['old.jpg']);
+ expect((await loadHistory())[0]).toMatchObject({ thumbnail: 'old.jpg', posterSec: 0.5 });
+ });
+ }
+
+ it('removes the downloaded video and partial poster when poster rendering throws', async () => {
+ state.thumbnailFailure = 'throw';
+ await expect(download()).rejects.toThrow('poster render failed');
+ expect(await readdir(PATHS.videos)).toEqual([]);
+ expect(await readdir(PATHS.videoThumbnails)).toEqual([]);
+ expect(await loadHistory()).toEqual([]);
+ });
+
+ it('resets a poster using a fresh name and removes its old timestamp and bytes', async () => {
+ await prepare('poster');
+ const result = await updateVideoPoster('existing', null);
+ expect(result.posterSec).toBeNull();
+ expect(result.thumbnail).not.toBe('old.jpg');
+ expect((await loadHistory())[0]).not.toHaveProperty('posterSec');
+ expect(await readdir(PATHS.videoThumbnails)).toEqual([result.thumbnail]);
+ });
+});
diff --git a/server/services/videoUpload.js b/server/services/videoUpload.js
index 5f1a77d9f4..762c70563e 100644
--- a/server/services/videoUpload.js
+++ b/server/services/videoUpload.js
@@ -28,6 +28,7 @@ import { MAX_BASE64_UPLOAD_BYTES } from '../lib/uploadLimits.js';
import { generateThumbnail, probeVideoDuration } from '../lib/ffmpeg.js';
import { mutateVideoHistory } from './videoGen/history.js';
import { videoGenEvents } from './videoGen/events.js';
+import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';
// Compatibility export for the separate remote browser-download path.
// User uploads stream to disk without this legacy JSON transport bound.
@@ -104,31 +105,37 @@ async function persistGalleryVideo(header, originalName, size, write) {
const filename = `${id}.${ext}`;
await ensureDir(PATHS.videos);
const outPath = join(PATHS.videos, filename);
- try {
- await write(outPath);
- // Both best-effort: a missing ffmpeg/ffprobe degrades to a thumbnail-less
- // entry (normalizeVideo renders a no-preview tile), never a failed upload.
- const [thumbnail, durationSec] = await Promise.all([
- generateThumbnail(outPath, id).catch(() => null),
- probeVideoDuration(outPath).catch(() => null),
- ]);
- const title = typeof originalName === 'string' && originalName.trim()
- ? originalName.trim().slice(0, 200)
- : '';
- const entry = buildUploadHistoryEntry({ id, filename, thumbnail, durationSec, title });
- await mutateVideoHistory((history) => { history.unshift(entry); return history; });
- // Let the live media-asset index hook index this immediately (same event
- // the generation and download paths emit). Reconcile is the backstop.
- videoGenEvents.emit('completed', { generationId: id, filename, path: `/data/videos/${filename}`, thumbnail });
- console.log(`📥 Saved uploaded gallery video: ${filename} (${(size / 1024 / 1024).toFixed(1)}MB)`);
- return entry;
- } catch (err) {
- // A throw between the byte write and the history write would orphan a
- // large file in data/videos with nothing pointing at it — mirror
- // downloadVideoIntoLibrary's cleanup-then-rethrow.
- await unlinkGuarded(outPath).catch(() => {});
- throw err;
- }
+ // Take admission before the first byte and before the shared history tail.
+ // Rollback belongs to the same lease; notifications follow the durable commit.
+ const entry = await withBackupAssetPublication(async () => {
+ try {
+ await write(outPath);
+ // Both best-effort: a missing ffmpeg/ffprobe degrades to a thumbnail-less
+ // entry (normalizeVideo renders a no-preview tile), never a failed upload.
+ const [thumbnail, durationSec] = await Promise.all([
+ generateThumbnail(outPath, id).catch(() => null),
+ probeVideoDuration(outPath).catch(() => null),
+ ]);
+ if (!thumbnail) await unlinkGuarded(join(PATHS.videoThumbnails, `${id}.jpg`)).catch(() => {});
+ const title = typeof originalName === 'string' && originalName.trim()
+ ? originalName.trim().slice(0, 200)
+ : '';
+ const entry = buildUploadHistoryEntry({ id, filename, thumbnail, durationSec, title });
+ await mutateVideoHistory((history) => { history.unshift(entry); return history; });
+ return entry;
+ } catch (err) {
+ // A throw between the byte write and the history write would orphan a
+ // large file in data/videos with nothing pointing at it — mirror
+ // downloadVideoIntoLibrary's cleanup-then-rethrow.
+ await unlinkGuarded(outPath).catch(() => {});
+ await unlinkGuarded(join(PATHS.videoThumbnails, `${id}.jpg`)).catch(() => {});
+ throw err;
+ }
+ });
+ // A throwing listener must not roll back bytes already named by history.
+ videoGenEvents.emit('completed', { generationId: id, filename, path: `/data/videos/${filename}`, thumbnail: entry.thumbnail });
+ console.log(`📥 Saved uploaded gallery video: ${filename} (${(size / 1024 / 1024).toFixed(1)}MB)`);
+ return entry;
}
export async function saveUploadedGalleryVideo(base64Data, originalName = '') {