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: keep voice and music-video asset references coherent in backups (#9982)

[._.]/ Adam Eivy83f30236ddbe
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index f405d5ceb5..33319ee2fd 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -65,6 +65,10 @@ 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) |
| Video-history deletion, including downloaded-video deletion (`videoGen/historyOps.js`) | Covered through file/history/index removal (#9982 partial) |
| 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) |
+| Music-library deletion (`pipeline/musicLibrary.js`) | Outstanding: its route intentionally leaves existing issue/project references to the removed file (#9982) |
+| Other voice artifact owners (fine-tune and benchmark outputs) and Music Video asset workflows | Outstanding (#9982) |
| Other durable replacement/deletion owners and final global readiness/invariant check | Outstanding (#9982) |
| Database restore execution and backend-cutover acceptance (`backup.js`, `databasePreflight.js`) | Covered (#9983) |
@@ -91,13 +95,22 @@ normalization/cropping and copying are included in the lease. Pending `rendering
entries can still name files that do not exist yet, and admission does not repair
pre-existing missing files or make failed writes transactional.
-The remaining inventory includes voice-profile asset copies (`voice/studio.js`), development
-artifact/vocal-stem import workflows (`musicVideo/devArtifactService.js`,
-`musicVideo/vocalStem.js`), direct render/index completion listeners, and the
-other completion paths above. Their persistence adapters and direct filesystem
-calls need workflow-level classification; independently locking `fileCore` or
-SQL primitives would not cover the gap between writes. No domain is newly
-excluded by this slice, and the final global readiness check is still pending.
+Voice Studio holds admission after inference has produced its WAV and before
+creating or copying final source assets, until the corresponding profile row
+commits or failed-write cleanup finishes. Music Video development artifacts
+validate their media policy outside admission, then hold one lease from the
+versioned file write through project-record mutation and cleanup. Vocal stems
+probe the master and upload outside admission, then hold one lease from library
+copy through the project update. A failed row write can still leave an
+unreferenced library stem; it cannot make a completed snapshot point at absent
+bytes.
+
+The remaining inventory includes music-library deletion, other voice artifacts,
+direct render/index completion listeners, and the other completion paths above.
+Their persistence adapters and direct filesystem calls still need workflow-level classification;
+independently locking `fileCore` or SQL primitives would not cover the gap
+between writes. No domain is newly excluded by this slice, and the final global
+readiness check is still pending.
This is part of [the cross-store consistency work](https://github.com/atomantic/PortOS/issues/9923).
Until every owner is covered, `status: ok` reports that the file
diff --git a/server/services/musicVideo/devArtifactService.js b/server/services/musicVideo/devArtifactService.js
index cbf7fcc005..45d6f98f76 100644
--- a/server/services/musicVideo/devArtifactService.js
+++ b/server/services/musicVideo/devArtifactService.js
@@ -15,6 +15,7 @@ import { musicVideoMediaMode } from '../../lib/musicVideoMediaPolicy.js';
import { extname } from 'path';
import { unlink } from 'fs/promises';
import { ServerError } from '../../lib/errorHandler.js';
+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
import { getProject, mutateProjectRecord } from './projects.js';
import { musicVideoEvents } from './events.js';
import {
@@ -75,24 +76,26 @@ async function storeVersion(projectId, {
if (artifactId) findDevArtifact(project, artifactId);
const id = artifactId || newDevArtifactId();
const version = nextDevArtifactVersion(project, artifactId);
- const { file, bytes } = await writeDevArtifactFile({
- projectId, artifactId: id, version, ext: ext === 'jpeg' ? 'jpg' : ext, buffer, tempPath,
- });
- const out = await mutateProjectRecord(projectId, (current) => {
- if (musicVideoMediaMode(current) !== musicVideoMediaMode(project)) {
- throw new ServerError('Media mode changed during the artifact upload — try again', { status: 409, code: 'DEV_ARTIFACT_CONFLICT' });
- }
- // A concurrent write took this version number: refuse rather than point
- // two versions at one file.
- if (nextDevArtifactVersion(current, artifactId) !== version) {
- throw new ServerError('Another version of this artifact was saved at the same time — try again', { status: 409, code: 'DEV_ARTIFACT_CONFLICT' });
- }
- return addDevArtifactVersion(current, {
- artifactId, id: artifactId ? null : id, kind, title, file, mimeType, bytes, source, status, notes,
+ const out = await withBackupAssetPublication(async () => {
+ const { file, bytes } = await writeDevArtifactFile({
+ projectId, artifactId: id, version, ext: ext === 'jpeg' ? 'jpg' : ext, buffer, tempPath,
+ });
+ return mutateProjectRecord(projectId, (current) => {
+ if (musicVideoMediaMode(current) !== musicVideoMediaMode(project)) {
+ throw new ServerError('Media mode changed during the artifact upload — try again', { status: 409, code: 'DEV_ARTIFACT_CONFLICT' });
+ }
+ // A concurrent write took this version number: refuse rather than point
+ // two versions at one file.
+ if (nextDevArtifactVersion(current, artifactId) !== version) {
+ throw new ServerError('Another version of this artifact was saved at the same time — try again', { status: 409, code: 'DEV_ARTIFACT_CONFLICT' });
+ }
+ return addDevArtifactVersion(current, {
+ artifactId, id: artifactId ? null : id, kind, title, file, mimeType, bytes, source, status, notes,
+ });
+ }).catch(async (err) => {
+ await discardDevArtifactFile(file);
+ throw err;
});
- }).catch(async (err) => {
- await discardDevArtifactFile(file);
- throw err;
});
console.log(`🗂️ Music Video dev artifact ${out.artifact.id.slice(4, 12)} v${version} saved for ${projectId.slice(0, 11)} (${out.artifact.kind}, ${mimeType})`);
publish(projectId, out.project, out.artifact);
diff --git a/server/services/musicVideo/mediaModes.test.js b/server/services/musicVideo/mediaModes.test.js
index 1cd5578049..2e3fe9897e 100644
--- a/server/services/musicVideo/mediaModes.test.js
+++ b/server/services/musicVideo/mediaModes.test.js
@@ -1,5 +1,5 @@
import { afterAll, describe, expect, it, vi } from 'vitest';
-import { mkdir, writeFile, stat } from 'node:fs/promises';
+import { mkdir, readFile, writeFile, stat } from 'node:fs/promises';
import { join } from 'node:path';
import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';
vi.mock('../../lib/paths.js', async (original) => makePathsProxy(await original(), { dataRoot: () => lazyTempDataRoot('mv-media-policy-') }));
@@ -10,6 +10,7 @@ vi.mock('./devArtifactStore.js', async (original) => {
const projects = await import('./projects.js');
const { importDocumentDirectory } = await import('./compositionDocument.js');
const { PATHS } = await import('../../lib/paths.js');
+const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');
const { assertMusicVideoMedia, musicVideoMediaMode } = await import('../../lib/musicVideoMediaPolicy.js');
const { castAndSetsAllowsImages, castAndSetsMedium } = await import('./castAndSetsDirection.js');
const { migrateMediaMode } = await import('../../../scripts/migrations/421-music-video-media-modes.js');
@@ -105,6 +106,45 @@ it('refuses a guide upload when the media mode narrows before its record commit
await expect(stat(tempPath)).rejects.toMatchObject({ code: 'ENOENT' });
});
+it('drains development artifact bytes and their project record before a backup cut', async () => {
+ const { saveGeneratedDevArtifact } = await import('./devArtifactService.js');
+ const store = await import('./devArtifactStore.js');
+ const original = await vi.importActual('./devArtifactStore.js');
+ const project = await projects.createProject({ name: 'Backup artifact', mediaMode: 'code-images' });
+ let reachFile;
+ let finishFile;
+ const atFile = new Promise(resolve => { reachFile = resolve; });
+ const fileGate = new Promise(resolve => { finishFile = resolve; });
+ store.writeDevArtifactFile.mockImplementationOnce(async input => {
+ const written = await original.writeDevArtifactFile(input);
+ reachFile();
+ await fileGate;
+ return written;
+ });
+ const saving = saveGeneratedDevArtifact(project.id, {
+ kind: 'storyboard', title: 'Example', html: '<svg>example</svg>',
+ });
+ await atFile;
+ expect((await projects.getProject(project.id)).devArtifacts || []).toEqual([]);
+ let cutAcquired = false;
+ const cut = acquireBackupSnapshotCut().then(release => {
+ cutAcquired = true;
+ return release;
+ });
+ await Promise.resolve();
+ expect(cutAcquired).toBe(false);
+ finishFile();
+ const { artifact } = await saving;
+ const release = await cut;
+ try {
+ const recorded = (await projects.getProject(project.id)).devArtifacts[0].versions[0];
+ expect(recorded.file).toBe(artifact.versions[0].file);
+ expect(await readFile(store.resolveDevArtifactFile(recorded.file), 'utf8')).toBe('<svg>example</svg>');
+ } finally {
+ release();
+ }
+});
+
it('blocks reselecting or approving retained raster guides, including embedded HTML, after narrowing', async () => {
const { importDevArtifact, saveGeneratedDevArtifact } = await import('./devArtifactService.js');
const { saveProductionDraft, approveProductionReview } = await import('./productionReviewService.js');
diff --git a/server/services/musicVideo/vocalStem.js b/server/services/musicVideo/vocalStem.js
index 9c2ef84ef6..941686c551 100644
--- a/server/services/musicVideo/vocalStem.js
+++ b/server/services/musicVideo/vocalStem.js
@@ -27,6 +27,7 @@ import { existsSync } from 'fs';
import { unlink } from 'fs/promises';
import { join } from 'path';
import { ServerError } from '../../lib/errorHandler.js';
+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
import { PATHS } from '../../lib/fileUtils.js';
import { probeVideoDuration, safeUnder } from '../../lib/ffmpeg.js';
import { importUploadedTrack } from '../pipeline/musicLibrary.js';
@@ -82,15 +83,17 @@ export async function attachVocalStem(projectId, { tempPath, originalName }) {
const masterPath = await resolveMasterAudioPath(project);
const [songSec, stemSec] = await Promise.all([probeVideoDuration(masterPath), probeVideoDuration(tempPath)]);
assertVocalStemTimebase(stemSec, songSec);
- const { filename } = await importUploadedTrack(tempPath, originalName);
- // The song may have been swapped while the files were probed; a stem
- // checked against the old master must not land on the new one.
- const current = await getProject(projectId);
- if (!current || audioSourceKey(current) !== audioSourceKey(project)) {
- await unlink(join(PATHS.music, filename)).catch(() => {});
- throw new ServerError('The project\'s song changed while the vocal stem was uploading. Upload it again.', { status: 409, code: 'MUSIC_VIDEO_AUDIO_CHANGED' });
- }
- return updateProject(projectId, { vocalStemFilename: filename, performanceConditioningSource: 'vocal-stem' });
+ return await withBackupAssetPublication(async () => {
+ const { filename } = await importUploadedTrack(tempPath, originalName);
+ // The song may have been swapped while the files were probed; a stem
+ // checked against the old master must not land on the new one.
+ const current = await getProject(projectId);
+ if (!current || audioSourceKey(current) !== audioSourceKey(project)) {
+ await unlink(join(PATHS.music, filename)).catch(() => {});
+ throw new ServerError('The project\'s song changed while the vocal stem was uploading. Upload it again.', { status: 409, code: 'MUSIC_VIDEO_AUDIO_CHANGED' });
+ }
+ return updateProject(projectId, { vocalStemFilename: filename, performanceConditioningSource: 'vocal-stem' });
+ });
} finally {
await unlink(tempPath).catch(() => {});
}
diff --git a/server/services/musicVideo/vocalStem.test.js b/server/services/musicVideo/vocalStem.test.js
new file mode 100644
index 0000000000..e62c6a36db
--- /dev/null
+++ b/server/services/musicVideo/vocalStem.test.js
@@ -0,0 +1,41 @@
+import { afterAll, expect, it, vi } from 'vitest';
+import { mkdir, readFile, 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 original => makePathsProxy(await original(), {
+ dataRoot: () => lazyTempDataRoot('mv-vocal-backup-'),
+}));
+vi.mock('./render.js', () => ({ resolveMasterAudioPath: async () => '/synthetic/master.wav' }));
+vi.mock('../../lib/ffmpeg.js', async original => ({ ...await original(), probeVideoDuration: vi.fn(async () => 10) }));
+
+const { PATHS } = await import('../../lib/paths.js');
+const { createProject, getProject } = await import('./projects.js');
+const { attachVocalStem } = await import('./vocalStem.js');
+const { probeVideoDuration } = await import('../../lib/ffmpeg.js');
+const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');
+
+afterAll(() => cleanupTempDataRoots());
+
+it('keeps a stem file and its project reference behind an active backup cut', async () => {
+ const project = await createProject({ name: 'Vocal example', mediaMode: 'code-images' });
+ await mkdir(PATHS.data, { recursive: true });
+ const tempPath = join(PATHS.data, 'synthetic-upload.wav');
+ const bytes = Buffer.from('synthetic audio');
+ await writeFile(tempPath, bytes);
+
+ const release = await acquireBackupSnapshotCut();
+ try {
+ const attaching = attachVocalStem(project.id, { tempPath, originalName: 'vocals.wav' });
+ await vi.waitFor(() => expect(probeVideoDuration).toHaveBeenCalledTimes(2));
+ await new Promise(resolve => setImmediate(resolve));
+ expect((await getProject(project.id)).vocalStemFilename).toBeFalsy();
+ expect(await readdir(PATHS.music).catch(error => error.code === 'ENOENT' ? [] : Promise.reject(error))).toEqual([]);
+ release();
+ const attached = await attaching;
+ expect((await getProject(project.id)).vocalStemFilename).toBe(attached.vocalStemFilename);
+ expect(await readFile(join(PATHS.music, attached.vocalStemFilename))).toEqual(bytes);
+ } finally {
+ release();
+ }
+});
diff --git a/server/services/voice/studio.js b/server/services/voice/studio.js
index b10173d490..56b4835f2e 100644
--- a/server/services/voice/studio.js
+++ b/server/services/voice/studio.js
@@ -2,6 +2,7 @@
import { randomUUID, createHash } from 'node:crypto';
import { mkdir, writeFile, copyFile, rm } from 'node:fs/promises';
import { join } from 'node:path';
+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
import { withTransaction } from '../../lib/db.js';
import { ServerError } from '../../lib/errorHandler.js';
import { synthesizeAuk } from './aukRuntime.js';
@@ -16,7 +17,6 @@ export async function createStudioVoice({ label, instructions, text, seed = 42,
}
const id = randomUUID();
const directory = profileArtifactDirectory(id);
- await mkdir(join(directory, 'source'), { recursive: true });
const filename = 'reference.wav';
const now = new Date().toISOString();
const profile = sanitizeVoiceProfile({
@@ -32,9 +32,16 @@ export async function createStudioVoice({ label, instructions, text, seed = 42,
engine: 'auk', modelRevision: result.modelRevision, effectiveControls: result.effectiveControls }] },
createdAt: now, updatedAt: now,
});
- return writeFile(join(directory, 'source', filename), result.wav)
- .then(() => persistVoiceProfile(profile))
- .catch(async error => { await rm(directory, { recursive: true, force: true }); throw error; });
+ return withBackupAssetPublication(async () => {
+ await mkdir(join(directory, 'source'), { recursive: true });
+ try {
+ await writeFile(join(directory, 'source', filename), result.wav);
+ return await persistVoiceProfile(profile);
+ } catch (error) {
+ await rm(directory, { recursive: true, force: true });
+ throw error;
+ }
+ });
}
export async function assignStudioVoice(profileId, { universeId, characterId, enableInteractive = false }) {
@@ -48,7 +55,6 @@ export async function assignStudioVoice(profileId, { universeId, characterId, en
}
const id = randomUUID();
const directory = profileArtifactDirectory(id);
- await mkdir(join(directory, 'source'), { recursive: true });
const now = new Date().toISOString();
const assigned = sanitizeVoiceProfile({ ...source, id, library: false,
binding: { universeId, characterId }, originProfileId: source.originProfileId || source.id,
@@ -71,5 +77,13 @@ export async function assignStudioVoice(profileId, { universeId, characterId, en
return persistVoiceProfile(assigned, client.query.bind(client));
});
};
- return save().catch(async error => { await rm(directory, { recursive: true, force: true }); throw error; });
+ return withBackupAssetPublication(async () => {
+ await mkdir(join(directory, 'source'), { recursive: true });
+ try {
+ return await save();
+ } catch (error) {
+ await rm(directory, { recursive: true, force: true });
+ throw error;
+ }
+ });
}
diff --git a/server/services/voice/studio.test.js b/server/services/voice/studio.test.js
index 24a4ed3b46..97671c6e0d 100644
--- a/server/services/voice/studio.test.js
+++ b/server/services/voice/studio.test.js
@@ -7,14 +7,19 @@ let root;
let records;
let statements;
let rejectInsert;
+let beforeInsert;
const synthesizeAuk = vi.fn();
const getUniverse = vi.fn();
vi.mock('./aukRuntime.js', () => ({ synthesizeAuk: (...args) => synthesizeAuk(...args) }));
vi.mock('../universeBuilder/crud.js', () => ({ getUniverse: (...args) => getUniverse(...args) }));
-vi.mock('../../lib/paths.js', () => ({ PATHS: { get voiceProfiles() { return root; } } }));
+vi.mock('../../lib/paths.js', async () => {
+ const actual = await vi.importActual('../../lib/paths.js');
+ return { ...actual, PATHS: { ...actual.PATHS, get voiceProfiles() { return root; } } };
+});
async function execute(sql, args = []) {
statements.push(sql);
if (sql.includes('INSERT INTO voice_profiles')) {
+ if (beforeInsert) await beforeInsert();
if (rejectInsert) throw new Error('database unavailable');
records.set(args[0], JSON.parse(args[4]));
}
@@ -34,13 +39,14 @@ vi.mock('../../lib/db.js', () => ({ query: (...args) => execute(...args), withTr
} }));
const { createStudioVoice, assignStudioVoice } = await import('./studio.js');
const { resolveCharacterVoice } = await import('./profiles.js');
+const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');
const input = { label: 'Example voice', instructions: 'Warm alto', text: 'Hello there.', seed: 42, genSeconds: 4, pitchSemitones: -2 };
const wav = Buffer.alloc(48);
wav.write('RIFF', 0); wav.write('WAVE', 8);
beforeEach(async () => {
root = await mkdtemp(join(tmpdir(), 'voice-studio-test-'));
- records = new Map(); statements = []; rejectInsert = false;
+ records = new Map(); statements = []; rejectInsert = false; beforeInsert = null;
synthesizeAuk.mockReset().mockResolvedValue({ wav, latencyMs: 3200, modelRevision: 'test-auK' });
getUniverse.mockReset().mockResolvedValue({ characters: [{ id: 'character-1' }, { id: 'character-2' }] });
});
@@ -84,4 +90,45 @@ describe('Voice Studio audition and casting workflow', () => {
await expect(assignStudioVoice(library.id, { universeId: 'universe-1', characterId: 'missing' })).rejects.toThrow('existing character');
expect(records.size).toBe(1);
});
+ it('drains a voice file and its row before a snapshot can copy either store', async () => {
+ let reachInsert;
+ let finishInsert;
+ const atInsert = new Promise(resolve => { reachInsert = resolve; });
+ const insertGate = new Promise(resolve => { finishInsert = resolve; });
+ beforeInsert = async () => { reachInsert(); await insertGate; };
+ const creating = createStudioVoice(input);
+ await atInsert;
+ expect(records.size).toBe(0);
+ expect(await readdir(root)).toHaveLength(1);
+
+ let cutAcquired = false;
+ const cut = acquireBackupSnapshotCut().then(release => {
+ cutAcquired = true;
+ return release;
+ });
+ await Promise.resolve();
+ expect(cutAcquired).toBe(false);
+
+ finishInsert();
+ const profile = await creating;
+ const release = await cut;
+ expect(records.get(profile.id).sourceAssets[0].filename).toBe('reference.wav');
+ expect(await readFile(join(root, profile.id, 'source/reference.wav'))).toEqual(wav);
+ release();
+ });
+ it('waits to copy an assigned voice until an active snapshot releases its cut', async () => {
+ const library = await createStudioVoice(input);
+ const release = await acquireBackupSnapshotCut();
+ try {
+ const assigning = assignStudioVoice(library.id, { universeId: 'universe-1', characterId: 'character-1' });
+ await vi.waitFor(() => expect(statements.some(sql => sql.includes('SELECT data FROM voice_profiles WHERE id'))).toBe(true));
+ expect(await readdir(root)).toEqual([library.id]);
+ release();
+ const assigned = await assigning;
+ expect(records.get(assigned.id).sourceAssets[0].filename).toBe('reference.wav');
+ expect(await readFile(join(root, assigned.id, 'source/reference.wav'))).toEqual(wav);
+ } finally {
+ release();
+ }
+ });
});