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 sprite completion, voice artifacts, music library and pipeline audio rows whole across backups (#9982)
Adam Eivya664edd516d6
diff --git a/docs/BACKUP.md b/docs/BACKUP.mdindex 7c56ebcd2c..67514bec2d 100644--- a/docs/BACKUP.md+++ b/docs/BACKUP.md@@ -68,15 +68,18 @@ Admission inventory (`withBackupAssetPublication`):| Universe Builder completion listeners: collection filing, canon entry-ref append, and sidecar enrichment (`universeBuilderCollectionHook.js`); character reference sheet copy and pointer stamp (`universeCharacterSheet.js`) | Covered (#9982 partial) || Creative Director evaluation frames: render-completion sampling (`creativeDirector/sceneRunner.js`) and the resume pass that re-samples missing frames in place (`creativeDirector/completionHook.js`) | Covered from the first `${jobId}-fN.jpg` write through the scene row that names them (#9982 partial) || Creative Director render settlement (scene status and auto-accept, plan-step settle, seed-frame wait) and Music Video production step settlement (`musicVideo/productionService.js`) | Reference-only: these write no bytes, and the render they name was on disk before its admitted completion published |-| Sprite animation completion: clip copy, frame packaging and run record (`sprites/localAnimationJobHook.js`) | Outstanding (#9982) |+| Sprite animation completion: clip copy, frame packaging and run record (`sprites/localAnimationJobHook.js`) | Covered from clip staging through the run record that names the packaged frames (#9982 partial) || 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) || 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) |-| Voice fine-tune and benchmark outputs (`voice/fineTuning.js`, `voice/profileBenchmarks.js`) and other Music Video asset workflows | Outstanding (#9982) |+| Music-library upload copy and deletion (`pipeline/musicLibrary.js`) | Covered (#9982 partial): the copy and the unlink each hold one lease; the delete route intentionally leaves existing issue/project references to the removed file |+| Voice benchmark audio and row (`voice/profileBenchmarks.js`), cloned-candidate recording and row (`voice/profiles.js`), and the fine-tune job record that names each sealed checkpoint (`voice/fineTuning.js`) | Covered (#9982 partial); promoting a checkpoint writes only a row naming bytes the job record already named |+| 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 |+| 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, LoRA registration and deletion, 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) |@@ -129,6 +132,22 @@ Creative Director frame sampling holds its lease while ffmpeg decodes theclip, a few seconds for a typical scene; the evaluator dispatch that followsstays outside it.+Sprite animation completion files the finished clip under one lease: staging the+MP4, decoding and packaging its frames, and the run record that names them. It+takes the lease before the per-record write tail, so a filing queued behind a+long Reprocess holds its lease while it waits and can stretch a cut's drain by+that wait. Voice benchmarks synthesize outside admission, then write every WAV+and the benchmark row under one lease. A fine-tune job's checkpoints are written+by the training process, which cannot be admitted, so the job record that first+names each sealed checkpoint takes the lease instead. The music library's upload+copy and its deletion each hold a lease; deletion leaves the issues and projects+that named the track pointing at the removed file, as before. The pipeline audio+routes (music generation, cue render, voice-over line render) hold the lease only+around the row commit: the sidecar or synthesizer has already written the WAV,+possibly while a cut was running, and a row that waits out the cut can only name+audio the snapshot copied, or nothing. Music library uploads need no lease of+their own at the row: the admitted import copies the file first.+**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 that@@ -140,12 +159,20 @@ and `outstanding` lists the owner ids still outside admission. An unrecognizedstatus counts as outstanding, never as covered. Snapshots written before thisfield existed carry no claim and must be treated as partial.-The remaining inventory includes sprite animation completion, music-library-deletion, voice fine-tune and benchmark outputs, other Music Video asset-workflows, and owners not yet classified. 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 excluded from the snapshot to satisfy the claim.+The remaining inventory is the `outstanding` entries in `backupAssetOwners.js`,+grouped by domain with the modules whose file-plus-record workflows still run+outside admission, plus an `unclassified-durable-owners` entry for anything a+code sweep did not reach. 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 excluded+from the snapshot to satisfy the claim.++When wrapping one of them, remember the order a cut works in: it copies files,+then dumps rows. A row that names new bytes therefore has to commit under the+lease unless the lease already covered the byte write. A deletion that removes+the row first and the bytes second is safe either way, because the dump that+follows the copy sees no row. A deletion that unlinks first, or one that leaves+rows naming the removed file, must hold the lease around the unlink.This is part of [the cross-store consistency work](https://github.com/atomantic/PortOS/issues/9923).While `assetConsistency.scope` is `admitted-owners`, `status: ok` reports thatdiff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.jsindex 61b704a33f..059370d2fb 100644--- a/server/lib/backupAssetOwners.js+++ b/server/lib/backupAssetOwners.js@@ -6,7 +6,11 @@* - `admitted`: holds `withBackupAssetPublication` from its first byte change* through the row that names (or stops naming) those bytes. Every listed* module calls it; `backupAssetOwners.test.js` keeps this list and the code- * in step in both directions.+ * in step in both directions. Where a long producer (a sidecar or child+ * process) writes the bytes in place, only the row commit takes the lease:+ * a cut copies files before it dumps rows, so a row that waits out the cut+ * either precedes it, with its bytes durable and copied, or follows it, with+ * 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.@@ -62,16 +66,150 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([],},{ id: 'music-video-production-settlement', status: 'reference-only', modules: ['services/musicVideo/productionService.js'] },- { id: 'sprite-animation-completion', status: 'outstanding', modules: ['services/sprites/localAnimationJobHook.js'] },- { id: 'music-library-deletion', status: 'outstanding', modules: ['services/pipeline/musicLibrary.js'] },+ { id: 'sprite-animation-completion', status: 'admitted', modules: ['services/sprites/localAnimationJobHook.js'] },+ { id: 'music-library-import-and-deletion', status: 'admitted', modules: ['services/pipeline/musicLibrary.js'] },{+ // Benchmark audio plus its row, the cloned-candidate recording plus its row,+ // and the fine-tune job record that names each sealed checkpoint. Promoting+ // a checkpoint writes only a row naming bytes the job record already named.id: 'voice-training-artifacts',+ status: 'admitted',+ modules: ['services/voice/fineTuning.js', 'services/voice/profileBenchmarks.js', 'services/voice/profiles.js'],+ },+ {+ // Generated and cue-rendered music and voice-over line audio land on disk+ // before the issue row that names them; the row commit takes the lease.+ id: 'pipeline-audio-stage-rows',+ status: 'admitted',+ modules: ['routes/pipeline/audio.js'],+ },+ {+ // Library uploads are copied by the admitted `musicLibrary.js` import, and+ // the track or issue row that names the copy commits after it. The Music+ // Designer upload route (`routes/tracks.js`) and the pipeline upload route+ // follow the same import-then-row order.+ id: 'music-library-attach-after-import',+ status: 'reference-only',+ modules: ['services/trackYoutubeImport.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+ // function: a module listed here may also hold already-admitted workflows.+ {+ // Reference lock, loop trim, atlas compile, asset delete and source import,+ // plus the grok-TUI lane's attach, which runs outside the completion hook.+ id: 'sprite-workflows',+ status: 'outstanding',+ modules: [+ 'services/sprites/reference.js', 'services/sprites/walkTrims.js', 'services/sprites/atlas.js',+ 'services/sprites/assets.js', 'services/sprites/importer.js', 'services/sprites/walk.js',+ 'services/sprites/animationTrackWorkflow.js',+ ],+ },+ {+ // 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.+ 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',+ ],+ },+ {+ // Local, cloud and federated finalize, derived clips (stitch, upscale,+ // timeline, HTML composition, Blender), poster replacement, upload and download.+ 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/codeAnimation/blenderRender.js', 'services/videoUpload.js', 'services/videoDownload.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+ // gallery upload, sidecar edits and deletion, not for its generation tail.+ id: 'image-generation-completion-tails',+ status: 'outstanding',+ modules: [+ 'services/imageGen/local.js', 'services/imageGen/agy.js', 'services/imageGen/codex.js',+ 'services/imageGen/grok.js', 'services/imageGen/fal.js', 'services/imageGen/external.js',+ 'services/imageGen/remote.js', 'services/imageGen/variants.js', 'services/mediaSketches.js',+ ],+ },+ {+ id: 'writers-room-drafts',+ status: 'outstanding',+ modules: ['services/writersRoom/local.js', 'services/writersRoom/sync.js', 'services/writersRoom/polish.js'],+ },+ {+ // Trained LoRA registration and checkpoint promotion, preview copies, and+ // the run, LoRA and dataset deletes.+ id: 'lora-training-registration-and-deletion',+ status: 'outstanding',+ modules: ['services/loraTraining/index.js', 'services/loras.js', 'routes/loraTraining.js', 'routes/loras.js'],+ },+ {+ // Generated HTML, package import and repair, run artifacts, and the final+ // stage whose soundtrack mux rewrites the MP4 before the history append.+ id: 'code-animation-projects',+ status: 'outstanding',+ modules: [+ 'services/codeAnimation/index.js', 'services/codeAnimation/projects.js', 'services/codeAnimation/stages.js',+ 'services/codeAnimation/projectFiles.js', 'services/codeAnimation/sound.js',+ ],+ },+ {+ // Peer asset and draft-body pulls, share bucket import, and the peer library sweep.+ id: 'peer-and-share-imports',+ status: 'outstanding',+ modules: [+ 'services/sharing/peerSyncAssets.js', 'services/sharing/importer.js', 'services/sharing/peerMediaLibrarySync.js',+ ],+ },+ {+ // Persistent Mind screenshot attachments, songbook attachments, catalog+ // ingredient media and voice memos, and round reference audio.+ id: 'attachments-and-catalog-media',status: 'outstanding',- modules: ['services/voice/fineTuning.js', 'services/voice/profileBenchmarks.js'],+ modules: [+ 'services/persistentMindAttachments.js', 'routes/brainSongbook.js', 'services/catalogMedia.js',+ 'services/catalogIngestSources.js', 'services/roundReferenceAudioImport.js',+ ],+ },+ {+ id: 'mood-board-imports',+ status: 'outstanding',+ modules: [+ 'services/moodBoard/collage.js', 'services/moodBoard/pinterest.js', 'services/moodBoard/privatePinterest.js',+ 'services/moodBoard/xPost.js', 'services/moodBoard/localize.js',+ ],+ },+ {+ id: 'image-to-3d-and-rigging',+ status: 'outstanding',+ modules: ['services/imageTo3d/models.js', 'services/rigging/autoSkin.js', 'services/rigging/retarget.js'],+ },+ {+ // ChatGPT archive import and memory-asset deletion, YouTube ingest, and the+ // digital twin and genome document stores.+ id: 'archive-and-document-imports',+ status: 'outstanding',+ modules: [+ 'services/chatgptZipImport.js', 'services/chatgptImport.js', 'services/youtubeIngest.js',+ 'services/digital-twin-documents.js', 'services/genome.js',+ ],},- // Music Video asset workflows beyond development artifacts and vocal stems,- // and every replacement/deletion owner this inventory has not classified yet.- { id: 'music-video-asset-workflows', status: 'outstanding', modules: [] },+ // Anything the sweep did not reach. A new asset owner lands here until it is+ // classified; the claim cannot become `global` while this entry exists.{ id: 'unclassified-durable-owners', status: 'outstanding', modules: [] },]);diff --git a/server/routes/pipeline/audio.js b/server/routes/pipeline/audio.jsindex b6ad132135..21496365ff 100644--- a/server/routes/pipeline/audio.js+++ b/server/routes/pipeline/audio.js@@ -37,6 +37,7 @@ import {} from '../../services/pipeline/musicGen.js';import { deriveAudioCues, preserveRenderedCues } from '../../services/pipeline/audioCues.js';import { uploadSingle } from '../../lib/multipart.js';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { mapServiceError } from './shared.js';const router = Router();@@ -245,28 +246,33 @@ router.post('/issues/:id/stages/audio/lines/:lineIdx/render', asyncHandler(asyncroute: 'studio',}).catch((err) => { throw mapServiceError(err); });- if (synthResult.provenance) {- await recordVoiceProfileRender({- issueId: issue.id,- lineId: line.id,+ // The WAV is already on disk. The render provenance row and the stage row+ // that name it commit under one lease, so a backup cut can never dump a row+ // naming audio its file copy had not reached (#9982).+ const { issue: updatedIssue, stage } = await withBackupAssetPublication(async () => {+ if (synthResult.provenance) {+ await recordVoiceProfileRender({+ issueId: issue.id,+ lineId: line.id,+ audioFilename: synthResult.filename,+ latencyMs: synthResult.latencyMs,+ durationMs: synthResult.durationMs,+ provenance: synthResult.provenance,+ });+ } else {+ await clearVoiceProfileRender({ issueId: issue.id, lineId: line.id });+ }+ const nextLines = [...lines];+ nextLines[lineIdx] = {+ ...line,+ audioJobId: null,audioFilename: synthResult.filename,- latencyMs: synthResult.latencyMs,- durationMs: synthResult.durationMs,- provenance: synthResult.provenance,+ };+ return issuesSvc.updateStage(req.params.id, 'audio', {+ status: 'edited',+ lines: nextLines,+ errorMessage: '',});- } else {- await clearVoiceProfileRender({ issueId: issue.id, lineId: line.id });- }- const nextLines = [...lines];- nextLines[lineIdx] = {- ...line,- audioJobId: null,- audioFilename: synthResult.filename,- };- const { issue: updatedIssue, stage } = await issuesSvc.updateStage(req.params.id, 'audio', {- status: 'edited',- lines: nextLines,- errorMessage: '',});res.json({issue: updatedIssue, stage, lineIdx,@@ -387,7 +393,10 @@ router.post('/issues/:id/stages/audio/music/generate', asyncHandler(async (req,durationSec: body.durationSec,modelId: body.modelId,}).catch((err) => { throw mapServiceError(err); });- const { issue: updatedIssue, stage } = await issuesSvc.updateStageWithLatest(+ // The sidecar wrote the WAV in place and may still have been writing while a+ // cut ran. The row that first names it waits for any open cut, so a dump can+ // never name a track its file copy did not reach (#9982).+ const { issue: updatedIssue, stage } = await withBackupAssetPublication(() => issuesSvc.updateStageWithLatest(req.params.id,'audio',(current) => ({@@ -396,7 +405,7 @@ router.post('/issues/:id/stages/audio/music/generate', asyncHandler(async (req,music: { source: MUSIC_SOURCE.GEN, trackFilename: gen.filename, label: gen.model },errorMessage: '',}),- ).catch((err) => { throw mapServiceError(err); });+ )).catch((err) => { throw mapServiceError(err); });res.json({ issue: updatedIssue, stage, music: stage.music, durationSec: gen.durationSec, modelId: gen.modelId, engine: gen.engine });}));@@ -580,7 +589,8 @@ router.post('/issues/:id/stages/audio/cues/:cueIdx/render', asyncHandler(async (}).catch((err) => { throw mapServiceError(err); });// Merge against the freshest persisted cue inside the write queue so a// concurrent re-derive can't clobber the render (the cue list is re-read here).- const { issue: updatedIssue, stage } = await issuesSvc.updateStageWithLatest(+ // The row that first names the WAV waits for any open backup cut (#9982).+ const { issue: updatedIssue, stage } = await withBackupAssetPublication(() => issuesSvc.updateStageWithLatest(req.params.id,'audio',(current) => {@@ -596,7 +606,7 @@ router.post('/issues/:id/stages/audio/cues/:cueIdx/render', asyncHandler(async (};return { cues: nextCues, errorMessage: '' };},- ).catch((err) => { throw mapServiceError(err); });+ )).catch((err) => { throw mapServiceError(err); });res.json({issue: updatedIssue, stage, cueIdx,cue: stage.cues[cueIdx],diff --git a/server/routes/pipeline/audioBackupAdmission.test.js b/server/routes/pipeline/audioBackupAdmission.test.jsnew file mode 100644index 0000000000..8d0a962aec--- /dev/null+++ b/server/routes/pipeline/audioBackupAdmission.test.js@@ -0,0 +1,140 @@+/** Pipeline audio routes that name a freshly written audio file in an issue row.+ * The WAV exists before the row does, so the row commit is the publication: a+ * backup cut must never dump a row naming audio its file copy had not reached+ * (#9982). Each row write is held at its commit seam. */+import { beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { request } from '../../lib/testHelper.js';+import { errorMiddleware } from '../../lib/errorHandler.js';++let beforeRowWrite = async () => {};+let rowWrites = [];+const rowWrite = async (label, result) => {+ await beforeRowWrite();+ rowWrites.push(label);+ return result;+};+const generateMusic = vi.fn();+const synthesizeToFile = vi.fn();+const noopFn = () => vi.fn();++vi.mock('../../services/pipeline/series.js', () => ({ getSeries: async () => ({ id: 'series-1', universeId: null }) }));+vi.mock('../../services/pipeline/seriesCanon.js', () => ({ getSeriesCanon: async () => ({}) }));+vi.mock('../../services/pipeline/issues.js', () => ({+ getIssue: async () => ({+ id: 'issue-1',+ seriesId: 'series-1',+ stages: { audio: { cues: [{ prompt: 'a calm bed' }], lines: [{ id: 'line-1', text: 'Hello there.' }] } },+ }),+ assertStageUnlocked: () => {},+ updateStageWithLatest: async () => rowWrite('stage', {+ issue: { id: 'issue-1' },+ stage: { music: { trackFilename: 'music-gen-1.wav' }, cues: [{ trackFilename: 'music-gen-1.wav' }] },+ }),+ updateStage: async () => rowWrite('stage', { issue: { id: 'issue-1' }, stage: { lines: [] } }),+}));+vi.mock('../../services/pipeline/audio.js', () => ({+ listAllVoices: noopFn(),+ parseVoiceId: noopFn(),+ extractDialogueLines: noopFn(),+ resolveVoiceForLine: () => null,+ synthesizeToFile: (...args) => synthesizeToFile(...args),+}));+vi.mock('../../services/pipeline/manuscriptNarration.js', () => ({ narrateProse: noopFn() }));+vi.mock('../../services/voice/tts.js', () => ({ synthesize: noopFn() }));+vi.mock('../../services/voice/profiles.js', () => ({+ resolveCharacterVoice: noopFn(),+ clearVoiceProfileRender: async () => rowWrite('render-cleared'),+ recordVoiceProfileRender: async () => rowWrite('render-recorded'),+}));+vi.mock('../../services/pipeline/musicLibrary.js', () => ({+ MUSIC_SOURCE: { UPLOAD: 'upload', LIBRARY: 'library', GEN: 'gen' },+ MUSIC_UPLOAD_MAX_BYTES: 1024,+ isSupportedMusicUpload: () => true,+ listMusicLibrary: noopFn(),+ importUploadedTrack: noopFn(),+ deleteMusicTrack: noopFn(),+ statMusicTrack: noopFn(),+}));+vi.mock('../../services/pipeline/musicGen.js', () => ({+ DEFAULT_ENGINE_ID: 'example-engine',+ ENGINES: {+ 'example-engine': {+ id: 'example-engine', name: 'Example', models: [{ id: 'example-model', name: 'Example model' }],+ defaultModelId: 'example-model', defaultDurationSec: 10, minDurationSec: 1, maxDurationSec: 60, installEnv: 'EXAMPLE',+ },+ },+ isEngineHealthy: async () => true,+ generateMusic: (...args) => generateMusic(...args),+}));+vi.mock('../../services/pipeline/audioCues.js', () => ({ deriveAudioCues: noopFn(), preserveRenderedCues: noopFn() }));+vi.mock('./shared.js', () => ({ mapServiceError: error => error }));++const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');+const { default: router } = await import('./audio.js');++const app = express();+app.use(express.json());+app.use(router);+app.use(errorMiddleware);++const deferred = () => {+ let resolve;+ const promise = new Promise(done => { resolve = done; });+ return { promise, resolve };+};+const settle = () => new Promise(resolve => setImmediate(resolve));+const settleSeveral = async () => { for (let i = 0; i < 8; i += 1) await settle(); };+const holdRowWrite = () => {+ const reached = deferred();+ const commit = deferred();+ beforeRowWrite = async () => { reached.resolve(); await commit.promise; };+ return { reached: reached.promise, commit: commit.resolve };+};+const post = (url, body = {}) => request(app).post(url).send(body).then(response => response);++const ROUTES = [+ { name: 'music generation', url: '/issues/issue-1/stages/audio/music/generate', body: { prompt: 'a calm bed' }, bytes: generateMusic },+ { name: 'cue render', url: '/issues/issue-1/stages/audio/cues/0/render', body: {}, bytes: generateMusic },+ { name: 'voice-over line render', url: '/issues/issue-1/stages/audio/lines/0/render', body: {}, bytes: synthesizeToFile },+];++beforeEach(() => {+ beforeRowWrite = async () => {};+ rowWrites = [];+ generateMusic.mockReset().mockResolvedValue({+ filename: 'music-gen-1.wav', durationSec: 10, modelId: 'example-model', model: 'Example model', engine: 'example-engine',+ });+ synthesizeToFile.mockReset().mockResolvedValue({+ filename: 'vo-1.wav', latencyMs: 10, durationMs: 1000, engine: 'kokoro', voiceId: 'kokoro:example',+ provenance: { profileId: 'profile-1', profileRevision: 1, engine: 'kokoro' },+ });+});++describe.each(ROUTES)('$name', ({ url, body, bytes }) => {+ it('drains a row commit already in flight before the cut proceeds', async () => {+ const hold = holdRowWrite();+ const response = post(url, body);+ await hold.reached;+ let cutReady = false;+ const cut = acquireBackupSnapshotCut().then(release => { cutReady = true; return release; });+ await settleSeveral();+ expect(cutReady).toBe(false);+ hold.commit();+ expect((await response).status).toBe(200);+ const release = await cut;+ expect(rowWrites.length).toBeGreaterThan(0);+ release();+ });++ it('keeps producing the audio during a cut but commits no row until it ends', async () => {+ const release = await acquireBackupSnapshotCut();+ const response = post(url, body);+ await vi.waitFor(() => expect(bytes).toHaveBeenCalledTimes(1));+ await settleSeveral();+ expect(rowWrites).toEqual([]);+ release();+ expect((await response).status).toBe(200);+ expect(rowWrites.length).toBeGreaterThan(0);+ });+});diff --git a/server/services/pipeline/musicLibrary.js b/server/services/pipeline/musicLibrary.jsindex 3e1e4dc159..36c02d010d 100644--- a/server/services/pipeline/musicLibrary.js+++ b/server/services/pipeline/musicLibrary.js@@ -27,6 +27,7 @@ import {copyFileGuarded,unlinkGuarded,} from '../../lib/fileUtils.js';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';// Mirror of the sanitizer's MUSIC_SOURCES set in `services/pipeline/issues.js`.// Exported so routes don't sprinkle bare strings; `'gen'` is reserved for the@@ -137,17 +138,22 @@ export async function listMusicLibrary() {* helper. Returns `{ filename, sizeBytes }`.*/export async function importUploadedTrack(tempPath, originalName) {- await ensureDir(PATHS.music);const filename = buildStoredFilename(originalName);const dest = join(PATHS.music, filename);- // copyFile + unlink instead of rename — the multipart helper writes to- // os.tmpdir(), which may sit on a different filesystem (rename across- // devices throws EXDEV on Linux). Copy works regardless; the temp file- // unlink is best-effort cleanup.- await copyFileGuarded(tempPath, dest);+ // The copy is the whole publication: a snapshot copying the library while it+ // runs would capture a truncated file under its final name (#9982). The temp+ // file lives outside `data/`, so its cleanup stays outside the lease.+ const sizeBytes = await withBackupAssetPublication(async () => {+ await ensureDir(PATHS.music);+ // copyFile + unlink instead of rename — the multipart helper writes to+ // os.tmpdir(), which may sit on a different filesystem (rename across+ // devices throws EXDEV on Linux). Copy works regardless.+ await copyFileGuarded(tempPath, dest);+ const s = await stat(dest).catch(() => null);+ return s?.size ?? 0;+ });await unlinkGuarded(tempPath).catch(() => {});- const s = await stat(dest).catch(() => null);- return { filename, sizeBytes: s?.size ?? 0 };+ return { filename, sizeBytes };}/**@@ -172,15 +178,22 @@ export async function statMusicTrack(filename) {* Delete a track from the library by stored filename. Returns true if the* file existed and was removed; false if it was already gone. Validates the* filename so a path-traversal attempt can't escape `PATHS.music`.+ *+ * Issues and projects keep naming the removed file on purpose (see the route),+ * so a snapshot copied before the unlink and dumped after it would carry rows+ * naming bytes it never captured. Holding the lease makes the unlink wait out+ * an open cut and a cut wait out an unlink in flight (#9982).*/export async function deleteMusicTrack(filename) {assertSafeMusicFilename(filename);const full = join(PATHS.music, filename);- try {- await unlinkGuarded(full);- return true;- } catch (err) {- if (err.code === 'ENOENT') return false;- throw err;- }+ return withBackupAssetPublication(async () => {+ try {+ await unlinkGuarded(full);+ return true;+ } catch (err) {+ if (err.code === 'ENOENT') return false;+ throw err;+ }+ });}diff --git a/server/services/pipeline/musicLibraryBackupAdmission.test.js b/server/services/pipeline/musicLibraryBackupAdmission.test.jsnew file mode 100644index 0000000000..a87d049588--- /dev/null+++ b/server/services/pipeline/musicLibraryBackupAdmission.test.js@@ -0,0 +1,96 @@+/** Music library import and deletion over real files. A backup cut must never+ * copy the library while an upload is half written, and must never let an+ * unlink remove a file the captured rows still name (#9982). */+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdir, mkdtemp, readdir, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';++// Every upload copy awaits `beforeCopy`, so a test can hold it mid-publication.+let beforeCopy = async () => {};+vi.mock('../../lib/fileUtils.js', async importOriginal => {+ const actual = await importOriginal();+ const paths = makePathsProxy(actual, { dataRoot: () => lazyTempDataRoot('portos-music-library-') });+ return new Proxy(paths, {+ get: (target, prop) => (prop === 'copyFileGuarded'+ ? async (...args) => { await beforeCopy(); return actual.copyFileGuarded(...args); }+ : target[prop]),+ });+});++const { PATHS } = await import('../../lib/fileUtils.js');+const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');+const { deleteMusicTrack, importUploadedTrack } = await import('./musicLibrary.js');++const deferred = () => {+ let resolve;+ const promise = new Promise(done => { resolve = done; });+ return { promise, resolve };+};+const settle = () => new Promise(resolve => setImmediate(resolve));+const settleSeveral = async () => { for (let i = 0; i < 5; i += 1) await settle(); };+const libraryFiles = () => readdir(PATHS.music).catch(() => []);+let scratch;+const makeUpload = async () => {+ const path = join(scratch, `upload-${Math.random().toString(36).slice(2)}.mp3`);+ await writeFile(path, 'synthetic audio');+ return path;+};++afterAll(async () => {+ await rm(scratch, { recursive: true, force: true });+ cleanupTempDataRoots();+});+beforeEach(async () => {+ beforeCopy = async () => {};+ scratch ||= await mkdtemp(join(tmpdir(), 'portos-music-upload-'));+ await rm(PATHS.music, { recursive: true, force: true });+ await mkdir(PATHS.music, { recursive: true });+});++describe('music library backup admission', () => {+ it('drains an upload already copying so the cut never reads a half-written library', async () => {+ const reached = deferred();+ const proceed = deferred();+ beforeCopy = async () => { reached.resolve(); await proceed.promise; };+ const upload = importUploadedTrack(await makeUpload(), 'song.mp3');+ await reached.promise;+ let cutReady = false;+ const cut = acquireBackupSnapshotCut().then(release => { cutReady = true; return release; });+ await settleSeveral();+ expect(cutReady).toBe(false);+ proceed.resolve();+ const { filename } = await upload;+ const release = await cut;+ expect(await libraryFiles()).toEqual([filename]);+ release();+ });++ it('holds an upload arriving during a cut until the snapshot is done', async () => {+ const release = await acquireBackupSnapshotCut();+ const upload = importUploadedTrack(await makeUpload(), 'song.mp3');+ await settleSeveral();+ expect(await libraryFiles()).toEqual([]);+ release();+ const { filename } = await upload;+ expect(await libraryFiles()).toEqual([filename]);+ });++ it('keeps a deleted track on disk until the cut that captured its rows finishes', async () => {+ await writeFile(join(PATHS.music, 'named-by-a-row.mp3'), 'synthetic audio');+ const release = await acquireBackupSnapshotCut();+ const deletion = deleteMusicTrack('named-by-a-row.mp3');+ await settleSeveral();+ expect(await libraryFiles()).toEqual(['named-by-a-row.mp3']);+ release();+ expect(await deletion).toBe(true);+ expect(await libraryFiles()).toEqual([]);+ });++ it('rejects an unsafe filename without taking admission', async () => {+ await expect(deleteMusicTrack('../outside.mp3')).rejects.toThrow();+ const release = await acquireBackupSnapshotCut({ timeoutMs: 50 });+ release();+ });+});diff --git a/server/services/sprites/localAnimationJobHook.js b/server/services/sprites/localAnimationJobHook.jsindex 013126c37f..af8daaab0d 100644--- a/server/services/sprites/localAnimationJobHook.js+++ b/server/services/sprites/localAnimationJobHook.js@@ -29,6 +29,7 @@import { join } from 'path';import { mediaJobEvents, listJobs } from '../mediaJobQueue/index.js';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { readJSONFile, atomicWrite } from '../../lib/fileUtils.js';import { spriteDir, runRelPath, SOURCE_CLIP_NAME, RUN_RECORD_NAME } from './paths.js';import { WALK_TRACK } from './animationTargets.js';@@ -63,6 +64,18 @@ const decodeSpriteAnimationJob = (job) => {* Both the staging and the attach run INSIDE the per-record write tail: the* clip lands at the same path a user-triggered Reprocess reads, and a copy racing* that read would hand ffmpeg a truncated MP4 and error a previously-good run.+ *+ * The whole settle also holds backup admission (#9982): the staged clip, the+ * decoded frames and manifest, and the run record that names them are one+ * publication, and a snapshot copying the sprite directory halfway through would+ * capture a run record whose frames it copied earlier. The lease is taken BEFORE+ * the tail, and synchronously, because this runs as a completion listener: the+ * queue's fan-out contract requires the lease to be held before the first await,+ * so a cut already draining for the job's own completion also waits for this+ * filing. No sprite workflow takes the lease while holding the tail, so the+ * order cannot deadlock; one that does later must take the lease first too.+ * A settle queued behind a long Reprocess holds its lease while it waits, which+ * can stretch a cut's drain by that wait.*/async function settleSpriteAnimationJob(job) {const decoded = decodeSpriteAnimationJob(job);@@ -71,7 +84,7 @@ async function settleSpriteAnimationJob(job) {const label = `sprite ${track} ${recordId}/${direction || 'row-0'}`;const runRel = runRelPath(runId);const videoAbs = join(spriteDir(recordId), runRel, 'generated', SOURCE_CLIP_NAME);- return withAnimationWriteTail(recordId, async () => {+ return withBackupAssetPublication(() => withAnimationWriteTail(recordId, async () => {// Settle a run ONCE. Neither attach looks at `run.status` — they guard only// frozen evidence (a finalized set, an approved run) — so re-entering here// for a run that is already `candidate` would re-stage the clip and re-run@@ -113,7 +126,7 @@ async function settleSpriteAnimationJob(job) {? attachTuiWalkResult(recordId, runId, videoAbs): attachTrackTuiResult(track, recordId, runId, videoAbs));return true;- });+ }));}let terminalHandler = null;diff --git a/server/services/sprites/localAnimationJobHook.test.js b/server/services/sprites/localAnimationJobHook.test.jsindex 6fff04bf6c..92da4bfc98 100644--- a/server/services/sprites/localAnimationJobHook.test.js+++ b/server/services/sprites/localAnimationJobHook.test.js@@ -12,6 +12,10 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { EventEmitter } from 'events';import { join } from 'path';+import {+ acquireBackupSnapshotCut, runOutsideBackupAssetPublication, withBackupAssetPublication,+} from '../../lib/backupSnapshotBoundary.js';+import { withAnimationWriteTail } from './animationWorkflow.js';const mediaJobEvents = new EventEmitter();let queuedJobs = [];@@ -304,6 +308,84 @@ describe('initSpriteLocalAnimationHook', () => {});});+// A cut must never land between staging a clip and the run record that names the+// frames packaged from it (#9982).+describe('backup admission', () => {+ const deferred = () => {+ let resolve;+ const promise = new Promise((done) => { resolve = done; });+ return { promise, resolve };+ };+ const settleTicks = async () => { for (let i = 0; i < 5; i += 1) await new Promise((resolve) => setImmediate(resolve)); };+ // Holds the attach open, so a test can request a cut while a filing is mid-flight.+ const holdAttach = () => {+ const reached = deferred();+ const finish = deferred();+ attachTuiWalkResult.mockImplementation(async () => { reached.resolve(); await finish.promise; });+ return { reached: reached.promise, finish: finish.resolve };+ };++ it('drains a settle already staging and attaching a clip', async () => {+ const hold = holdAttach();+ const settling = settleSpriteAnimationJob(walkJob());+ await hold.reached;+ let cutReady = false;+ const cut = acquireBackupSnapshotCut().then((release) => { cutReady = true; return release; });+ await settleTicks();+ expect(cutReady).toBe(false);+ hold.finish();+ expect(await settling).toBe(true);+ (await cut)();+ });++ it('stages and files nothing for a job that settles during a cut', async () => {+ const release = await acquireBackupSnapshotCut();+ const settling = settleSpriteAnimationJob(walkJob());+ await settleTicks();+ expect(collectLocalAnimationClip).not.toHaveBeenCalled();+ expect(attachTuiWalkResult).not.toHaveBeenCalled();+ release();+ expect(await settling).toBe(true);+ expect(attachTuiWalkResult).toHaveBeenCalledTimes(1);+ });++ it('lets a cut already waiting on the job\'s own completion also wait for a filing queued behind the record\'s write tail', async () => {+ initSpriteLocalAnimationHook();+ const hold = holdAttach();+ const tailHeld = deferred();+ const blocker = withAnimationWriteTail('hero', () => tailHeld.promise);+ const completion = deferred();+ // The queue's completion lease, whose fan-out reaches this listener.+ const completing = withBackupAssetPublication(async () => {+ await completion.promise;+ runOutsideBackupAssetPublication(() => mediaJobEvents.emit('completed', walkJob()));+ });+ let cutReady = false;+ const cut = acquireBackupSnapshotCut().then((release) => { cutReady = true; return release; });+ await settleTicks();+ completion.resolve();+ await completing;+ // The completion's own lease is gone and the filing still waits for the tail:+ // only the listener's own lease, taken at emit time, keeps the cut waiting.+ await settleTicks();+ expect(cutReady).toBe(false);+ tailHeld.resolve();+ await blocker;+ await hold.reached;+ await settleTicks();+ expect(cutReady).toBe(false);+ hold.finish();+ (await cut)();+ expect(attachTuiWalkResult).toHaveBeenCalledTimes(1);+ });++ it('takes no lease for a media job that is not a sprite render', async () => {+ const release = await acquireBackupSnapshotCut();+ expect(await settleSpriteAnimationJob({ kind: 'video', params: {} })).toBe(false);+ release();+ });+});+describe('reconcileSettledSpriteJobs (boot pass)', () => {it('files jobs that reached a terminal state while the process was DOWN', async () => {// These emit nothing — they are simply sitting in the restored archive. Thediff --git a/server/services/voice/fineTuning.js b/server/services/voice/fineTuning.jsindex 0d2a4a1f11..0c903a6277 100644--- a/server/services/voice/fineTuning.js+++ b/server/services/voice/fineTuning.js@@ -17,6 +17,7 @@ import { randomUUID } from 'node:crypto';import { existsSync } from 'node:fs';import { mkdir, readdir } from 'node:fs/promises';import { dirname, join } from 'node:path';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { spawn } from '../../lib/childProcess.js';import { ServerError } from '../../lib/errorHandler.js';import { atomicWrite, readJSONFileStrict } from '../../lib/fileUtils.js';@@ -91,6 +92,12 @@ const serializableJob = ({/*** Write the job record to disk. Writes are chained per job because `close` and* `error` can both fire for one child and each rewrites the same file.+ *+ * The runner seals a checkpoint before reporting it, so this write is the moment+ * a checkpoint becomes named. It takes backup admission: a snapshot that copied+ * the run directory before a new checkpoint landed must not capture a record+ * listing it afterwards. The runner's own writes are outside the process and+ * cannot be admitted, but nothing names them until this write (#9982).*/const persistJob = (jobState) => {// Capture the durable state when this write is queued. Otherwise a checkpoint@@ -98,7 +105,7 @@ const persistJob = (jobState) => {// object and can race the terminal write out of order.const record = structuredClone(serializableJob(jobState));jobState.persistChain = (jobState.persistChain || Promise.resolve())- .then(() => atomicWrite(jobRecordPath(jobState.profileId, jobState.id), record))+ .then(() => withBackupAssetPublication(() => atomicWrite(jobRecordPath(jobState.profileId, jobState.id), record))).catch((err) => console.error(`❌ Failed to persist fine-tune job ${jobState.id}: ${err.message}`));return jobState.persistChain;};diff --git a/server/services/voice/fineTuning.test.js b/server/services/voice/fineTuning.test.jsindex 25fa36faf4..530a514c61 100644--- a/server/services/voice/fineTuning.test.js+++ b/server/services/voice/fineTuning.test.js@@ -4,6 +4,7 @@ import { mkdtemp, rm, mkdir, writeFile, readFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';import { SSE_CLEANUP_DELAY_MS } from '../../lib/sseUtils.js';+import { acquireBackupSnapshotCut } from '../../lib/backupSnapshotBoundary.js';let voiceProfilesRoot = '';const queryMock = vi.fn();@@ -14,6 +15,13 @@ const queryMock = vi.fn();let spawnOverride = null;let runtimeOverride = null;+// Every sidecar write is recorded when it is ATTEMPTED, so a test can tell a write+// held behind backup admission from one that is merely still in flight.+const sidecarWrites = [];+vi.mock('../../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, atomicWrite: (path, ...rest) => { sidecarWrites.push(path); return actual.atomicWrite(path, ...rest); } };+});vi.mock('../../lib/db.js', () => ({ query: (...args) => queryMock(...args) }));vi.mock('../../lib/paths.js', async () => {const actual = await vi.importActual('../../lib/paths.js');@@ -250,6 +258,30 @@ describe('fineTuning', () => {});});+ it('lists a checkpoint in job.json only after an open backup cut releases (#9982)', async () => {+ queryMock.mockResolvedValue({ rows: [{ data: PROFILE }] });+ await seedSourceAudio();+ const scripted = useScriptedRunner();+ const { jobId } = await startFineTuningJob({ profileId: PROFILE.id, epochs: 2, checkpointInterval: 20 });+ const readCheckpoints = async () => JSON.parse(await readFile(jobRecordPath(jobId), 'utf8')).checkpoints;+ expect(await readCheckpoints()).toEqual([]);+ const writesBefore = sidecarWrites.length;++ // The runner sealed checkpoint 20 while a snapshot was copying this run's+ // directory. The record naming it must wait, or the snapshot would list a+ // checkpoint whose bytes it copied before they existed.+ const release = await acquireBackupSnapshotCut();+ scripted().emitFrames(checkpointFrame(jobId, 20));+ for (let tick = 0; tick < 5; tick += 1) await new Promise((resolve) => setImmediate(resolve));+ expect(sidecarWrites).toHaveLength(writesBefore);+ expect(await readCheckpoints()).toEqual([]);++ release();+ await vi.waitFor(async () => expect((await readCheckpoints()).map((c) => c.step)).toEqual([20]));+ scripted().exit(0);+ await drainJobRecord(jobId);+ });+it('settles a cancelled job as cancelled even though the abort also fires an error', async () => {queryMock.mockResolvedValue({ rows: [{ data: PROFILE }] });await seedSourceAudio();diff --git a/server/services/voice/profileBenchmarks.js b/server/services/voice/profileBenchmarks.jsindex 6644cd1e80..e627f7afec 100644--- a/server/services/voice/profileBenchmarks.js+++ b/server/services/voice/profileBenchmarks.js@@ -4,6 +4,7 @@ import { randomUUID } from 'node:crypto';import { mkdir, writeFile } from 'node:fs/promises';import { join } from 'node:path';import { synthesize } from './tts.js';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { ServerError } from '../../lib/errorHandler.js';import {getProfileForSynthesis,@@ -33,35 +34,41 @@ const benchmarkLinesFor = (profile) => {* Render each benchmark line sequentially. Local engines are intentionally* serialized: Kokoro has one resident model and Piper/Qwen spawn processes,* so concurrency only increases contention and muddles timings.+ *+ * Synthesis stays outside backup admission because it runs for as long as the+ * engine takes. The renders are held in memory and the WAV files plus the+ * benchmark row that names them are published under one lease, so a snapshot+ * never carries a benchmark naming audio it did not copy (#9982).*/export async function renderProfileBenchmark(profileId, { signal } = {}) {const profile = await getProfileForSynthesis(profileId, 'studio');const directory = join(profileArtifactDirectory(profile.id), 'benchmarks', `v${profile.version}`);- await mkdir(directory, { recursive: true });- const lines = [];+ const renders = [];for (const [index, line] of benchmarkLinesFor(profile).entries()) {const result = await synthesize(line.text, {profileId: profile.id,route: 'studio',signal,});- const filename = `${String(index + 1).padStart(2, '0')}-${line.key}.wav`;- await writeFile(join(directory, filename), result.wav);- lines.push({- key: line.key,- text: line.text,- filename: `voice-profiles/${profile.id}/benchmarks/v${profile.version}/${filename}`,- latencyMs: result.latencyMs,- engine: result.engine,- modelRevision: result.provenance?.modelRevision || profile.modelRevision,- effectiveControls: result.provenance?.effectiveControls || { rate: null },- });+ renders.push({ line, result, filename: `${String(index + 1).padStart(2, '0')}-${line.key}.wav` });}- return saveProfileBenchmark(profile, {- profileRevision: profile.version,- renderedAt: new Date().toISOString(),- lines,- mastering: profile.mastering,+ return withBackupAssetPublication(async () => {+ await mkdir(directory, { recursive: true });+ await Promise.all(renders.map(({ filename, result }) => writeFile(join(directory, filename), result.wav)));+ return saveProfileBenchmark(profile, {+ profileRevision: profile.version,+ renderedAt: new Date().toISOString(),+ lines: renders.map(({ line, result, filename }) => ({+ key: line.key,+ text: line.text,+ filename: `voice-profiles/${profile.id}/benchmarks/v${profile.version}/${filename}`,+ latencyMs: result.latencyMs,+ engine: result.engine,+ modelRevision: result.provenance?.modelRevision || profile.modelRevision,+ effectiveControls: result.provenance?.effectiveControls || { rate: null },+ })),+ mastering: profile.mastering,+ });});}diff --git a/server/services/voice/profiles.js b/server/services/voice/profiles.jsindex 75d4431e90..e0798e1c8a 100644--- a/server/services/voice/profiles.js+++ b/server/services/voice/profiles.js@@ -10,6 +10,7 @@import { createHash, randomUUID } from 'node:crypto';import { mkdir } from 'node:fs/promises';import { join } from 'node:path';+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';import { query } from '../../lib/db.js';import { ServerError } from '../../lib/errorHandler.js';import { PATHS } from '../../lib/paths.js';@@ -391,10 +392,7 @@ export async function createClonedVoiceCandidate({const profileId = randomUUID();const profileDir = profileDirectory(profileId);const sourceDir = join(profileDir, 'source');- await mkdir(sourceDir, { recursive: true });-const safePath = join(sourceDir, cleanFilename);- await writeFileGuarded(safePath, audioBuffer);const sha256 = createHash('sha256').update(audioBuffer).digest('hex');const now = timestamp();@@ -437,7 +435,13 @@ export async function createClonedVoiceCandidate({updatedAt: now,});- return persist(next);+ // The source recording and the row that names it publish under one lease, so+ // a snapshot never carries a candidate whose consented recording it lacks (#9982).+ return withBackupAssetPublication(async () => {+ await mkdir(sourceDir, { recursive: true });+ await writeFileGuarded(safePath, audioBuffer);+ return persist(next);+ });}/**diff --git a/server/services/voice/voiceBackupAdmission.test.js b/server/services/voice/voiceBackupAdmission.test.jsnew file mode 100644index 0000000000..2424c54905--- /dev/null+++ b/server/services/voice/voiceBackupAdmission.test.js@@ -0,0 +1,145 @@+/** Voice profile asset publication over real files, with the profile row write+ * held at its commit seam. A backup cut must never land between the audio a+ * profile names and the row that names it (#9982). */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdtemp, readdir, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++let root;+let profile;+let beforeRowWrite = async () => {};+let rowWrites;+const synthesize = vi.fn();+vi.mock('./tts.js', () => ({ synthesize: (...args) => synthesize(...args) }));+vi.mock('../../lib/paths.js', async () => {+ const actual = await vi.importActual('../../lib/paths.js');+ return { ...actual, PATHS: { ...actual.PATHS, get voiceProfiles() { return root; } } };+});+// A single in-memory profile row. Every row write awaits `beforeRowWrite`.+vi.mock('../../lib/db.js', () => ({+ query: async (sql, args = []) => {+ if (sql.includes('SELECT data FROM voice_profiles WHERE id')) return { rows: profile ? [{ data: profile }] : [] };+ if (sql.includes('UPDATE voice_profiles SET')) {+ await beforeRowWrite();+ rowWrites.push('update');+ profile = { ...profile, benchmark: { ...profile.benchmark, ...JSON.parse(args[1]).benchmark } };+ return { rows: [{ data: profile }] };+ }+ if (sql.includes('INSERT INTO voice_profiles')) {+ await beforeRowWrite();+ rowWrites.push('insert');+ profile = JSON.parse(args[4]);+ return { rows: [] };+ }+ return { rows: [] };+ },+}));++const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');+const { createClonedVoiceCandidate } = await import('./profiles.js');+const { VOICE_PROFILE_BENCHMARK_LINES, renderProfileBenchmark } = await import('./profileBenchmarks.js');++const PROFILE_ID = '11111111-1111-4111-8111-111111111111';+const LINE_COUNT = VOICE_PROFILE_BENCHMARK_LINES.length;+const deferred = () => {+ let resolve;+ const promise = new Promise(done => { resolve = done; });+ return { promise, resolve };+};+const settle = () => new Promise(resolve => setImmediate(resolve));+const settleSeveral = async () => { for (let i = 0; i < 5; i += 1) await settle(); };+const holdRowWrite = () => {+ const reached = deferred();+ const commit = deferred();+ beforeRowWrite = async () => { reached.resolve(); await commit.promise; };+ return { reached: reached.promise, commit: commit.resolve };+};+const filesUnder = path => readdir(path).catch(() => []);++beforeEach(async () => {+ root = await mkdtemp(join(tmpdir(), 'voice-admission-test-'));+ beforeRowWrite = async () => {};+ rowWrites = [];+ profile = {+ id: PROFILE_ID, version: 1, label: 'Example Character', kind: 'preset', engine: 'kokoro', voiceId: 'kokoro:example',+ binding: { universeId: 'universe-1', characterId: 'character-1' },+ routes: { studio: { enabled: true }, interactive: { enabled: false } },+ mastering: { chain: ['preset-output:unprocessed'] },+ approval: { status: 'approved', approvedAt: '2026-01-01T00:00:00.000Z', benchmarkRevision: 1 },+ createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',+ };+ synthesize.mockReset().mockResolvedValue({ wav: Buffer.from('synthetic wav'), latencyMs: 5, engine: 'kokoro', provenance: {} });+});+afterEach(async () => { await rm(root, { recursive: true, force: true }); });++describe('voice benchmark publication', () => {+ const benchmarkDir = () => join(root, PROFILE_ID, 'benchmarks', 'v1');+ // What a snapshot holds: the audio copied and the benchmark lines the row names.+ const capture = async () => ({ files: (await filesUnder(benchmarkDir())).length, named: profile.benchmark?.lines?.length ?? 0 });++ it('drains audio already written through the benchmark row that names it', async () => {+ const hold = holdRowWrite();+ const render = renderProfileBenchmark(PROFILE_ID);+ await hold.reached;+ let cutReady = false;+ const cut = acquireBackupSnapshotCut().then(release => { cutReady = true; return release; });+ await settleSeveral();+ expect(cutReady).toBe(false);+ hold.commit();+ await render;+ const release = await cut;+ expect(await capture()).toEqual({ files: LINE_COUNT, named: LINE_COUNT });+ release();+ });++ it('keeps synthesis running during a cut but publishes no audio or row until it ends', async () => {+ const release = await acquireBackupSnapshotCut();+ const render = renderProfileBenchmark(PROFILE_ID);+ await vi.waitFor(() => expect(synthesize).toHaveBeenCalledTimes(LINE_COUNT));+ await settleSeveral();+ expect(await capture()).toEqual({ files: 0, named: 0 });+ expect(rowWrites).toEqual([]);+ release();+ await render;+ expect(await capture()).toEqual({ files: LINE_COUNT, named: LINE_COUNT });+ });+});++describe('cloned voice candidate publication', () => {+ const clone = () => createClonedVoiceCandidate({+ universeId: 'universe-1', characterId: 'character-1', audioBuffer: Buffer.from('synthetic recording'),+ filename: 'sample.wav', performerConsentConfirmed: true,+ });+ // The candidate's directory is minted per call, so look it up from the row.+ const capture = async () => ({+ files: profile?.id && profile.id !== PROFILE_ID ? await filesUnder(join(root, profile.id, 'source')) : [],+ named: profile?.id && profile.id !== PROFILE_ID ? profile.sourceAssets.map(asset => asset.filename) : [],+ });++ it('drains a recording already written through the candidate row that names it', async () => {+ const hold = holdRowWrite();+ const creation = clone();+ await hold.reached;+ let cutReady = false;+ const cut = acquireBackupSnapshotCut().then(release => { cutReady = true; return release; });+ await settleSeveral();+ expect(cutReady).toBe(false);+ hold.commit();+ await creation;+ const release = await cut;+ expect(await capture()).toEqual({ files: ['sample.wav'], named: ['sample.wav'] });+ release();+ });++ it('writes neither the recording nor the row while a cut is open', async () => {+ const release = await acquireBackupSnapshotCut();+ const creation = clone();+ await settleSeveral();+ expect(await filesUnder(root)).toEqual([]);+ expect(rowWrites).toEqual([]);+ release();+ await creation;+ expect(await capture()).toEqual({ files: ['sample.wav'], named: ['sample.wav'] });+ });+});