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 Code Animation renders and revisions whole across backups (#9982)

[._.]/ Adam Eivy9c48926a0ddf
diff --git a/docs/BACKUP.md b/docs/BACKUP.md
index 6f36a20d0b..5c7f782618 100644
--- a/docs/BACKUP.md
+++ b/docs/BACKUP.md
@@ -90,7 +90,9 @@ Admission inventory (`withBackupAssetPublication`):
| Rigging and animation retarget (`rigging/autoSkin.js`, `rigging/retarget.js`) | Covered (#9982 partial): the pair is published into its own directory and verified outside admission; the row that first names it takes the lease |
| Catalog ingredient media and voice-memo scraps, imported round reference audio, Persistent Mind screenshots and songbook attachments (`catalogMedia.js`, `catalogIngestSources.js`, `roundReferenceAudioImport.js`, `persistentMindAttachments.js`, `routes/brainSongbook.js`) | Covered (#9982 partial): the row that first names a landed file takes the lease; the file-backed Persistent Mind and songbook records hold it through their deletions too |
| Mood board re-hosting, Pinterest and X imports, frame extraction and collages (`moodBoard/*.js`) | Covered (#9982 partial): downloads and renders run outside admission; the board row that first names them, and each in-place rewrite of a URL-keyed download, take the lease |
-| Remaining durable owners, classified by domain in `backupAssetOwners.js` | Outstanding (#9982): sprites, video generation, image generation tails, code animation, peer and share imports, archive and document imports |
+| Code Animation generated HTML, package import and repair revisions, production stage-run artifacts, Blender film publication and the soundtrack mux install (`codeAnimation/index.js`, `projects.js`, `stages.js`, `blenderRender.js`, `sound.js`) | Covered (#9982 partial): write-once revision trees and run artifacts land first, and the revision, run or history row that first names them commits under the lease; the mux's in-place install over an already-named render takes it too |
+| Code Animation export staging and output acceptance (`codeAnimation/export.js`, `codeAnimation/acceptance.js`) | Reference-only: staging directories and worker workspaces are scratch no row names, and acceptance names a render that was already durable |
+| Remaining durable owners, classified by domain in `backupAssetOwners.js` | Outstanding (#9982): sprites, video generation, image generation tails, peer and share imports, 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) |
@@ -211,6 +213,19 @@ 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.
+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
+fresh write-once directory outside admission, then commits the revision row
+under the lease; the import's `staging` run row names that directory before
+its bytes land, but it is never a revision and a restart marks it interrupted.
+Every production run-row write takes the lease, because the row is what first
+names the stage's frames, soundtrack WAV and Blender bake. A Blender film is
+copied under a fresh name and muxed before its history entry commits under the
+lease. A browser render's history entry is written by the HTML-composition job
+(still outstanding with video generation), so the soundtrack mux holds the lease
+across its in-place install over that file, but not across the encode.
+
**Snapshot consistency claim.** `server/lib/backupAssetOwners.js` inventories
each durable owner as `admitted`, `reference-only` or `outstanding`, and its
test fails when an `admitted` entry stops taking the lease or a module that
diff --git a/server/lib/backupAssetOwners.js b/server/lib/backupAssetOwners.js
index 2669657104..2487943245 100644
--- a/server/lib/backupAssetOwners.js
+++ b/server/lib/backupAssetOwners.js
@@ -224,6 +224,30 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([
'services/moodBoard/xPost.js', 'services/moodBoard/localize.js', 'services/moodBoard/index.js',
],
},
+ {
+ // Generated HTML and the completed job row naming it are one lease. A
+ // package import or repair stages a write-once revision tree, and the
+ // revision row that first names it commits under the lease. Stage-run
+ // artifacts (frames, soundtrack WAV, Blender bake) are write-once files the
+ // run row first names, so every run-row write takes the lease. A Blender
+ // film is copied under a fresh name and its history entry commits under the
+ // lease; the soundtrack mux installs over an already-named browser render,
+ // so that in-place install takes it too.
+ id: 'code-animation-projects',
+ status: 'admitted',
+ modules: [
+ 'services/codeAnimation/index.js', 'services/codeAnimation/projects.js', 'services/codeAnimation/stages.js',
+ 'services/codeAnimation/sound.js', 'services/codeAnimation/blenderRender.js',
+ ],
+ },
+ {
+ // Export staging directories and contained-worker workspaces are scratch no
+ // row names. Accepting an output stamps a row naming a render whose bytes
+ // and run row were already durable.
+ id: 'code-animation-staging-and-acceptance',
+ status: 'reference-only',
+ modules: ['services/codeAnimation/export.js', 'services/codeAnimation/acceptance.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
@@ -241,7 +265,7 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([
},
{
// Local, cloud and federated finalize, derived clips (stitch, upscale,
- // timeline, HTML composition, Blender), poster replacement, upload and download.
+ // timeline, HTML composition), poster replacement, upload and download.
id: 'video-generation-finalize-and-derived-clips',
status: 'outstanding',
modules: [
@@ -249,7 +273,7 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([
'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',
+ 'services/videoUpload.js', 'services/videoDownload.js',
],
},
{
@@ -264,16 +288,6 @@ export const BACKUP_ASSET_OWNERS = Object.freeze([
'services/imageGen/remote.js', 'services/imageGen/variants.js', 'services/mediaSketches.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',
diff --git a/server/services/codeAnimation/backupAdmission.test.js b/server/services/codeAnimation/backupAdmission.test.js
new file mode 100644
index 0000000000..a9e0763ec8
--- /dev/null
+++ b/server/services/codeAnimation/backupAdmission.test.js
@@ -0,0 +1,246 @@
+/**
+ * Code Animation file-plus-row workflows against a backup cut (#9982). Each
+ * writes its bytes (generated HTML, a write-once revision tree, run artifacts,
+ * a published MP4) before the row that first names them, so that row commits
+ * under the admission lease: a cut that arrives mid-commit drains it, and a
+ * commit that arrives during a cut waits until the cut is released. Providers,
+ * renders and the database are doubled; revision and run files are real.
+ */
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdir, readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { createHash, randomUUID } from 'crypto';
+import { lazyTempDataRoot, makePathsProxy, cleanupTempDataRoots } from '../../lib/mockPathsDataRoot.js';
+
+vi.mock('../../lib/paths.js', async importOriginal =>
+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('code-animation-backup-') }));
+vi.mock('../../lib/databaseMaintenanceJournal.js', async importOriginal => ({
+ ...(await importOriginal()),
+ assertDatabaseAdmission: () => {},
+}));
+vi.mock('../socket.js', () => ({ emitCodeAnimationChanged: vi.fn() }));
+const store = vi.hoisted(() => ({
+ getProjectRecord: vi.fn(), getRevisionRecord: vi.fn(), startImportRecord: vi.fn(), commitImportRecord: vi.fn(),
+ failImportRecord: vi.fn(), startStageRun: vi.fn(), saveStageRun: vi.fn(), reserveRunBytes: vi.fn(),
+ commitRepairRevision: vi.fn(),
+}));
+vi.mock('./projectStore.js', () => store);
+const jobs = vi.hoisted(() => ({ saveCodeAnimationJobRecord: vi.fn(), saveCodeAnimationHtml: vi.fn() }));
+vi.mock('./jobStore.js', async importOriginal => ({ ...(await importOriginal()), ...jobs }));
+vi.mock('../providers.js', () => ({ getProviderById: vi.fn(async () => ({ id: 'example-provider', type: 'api', enabled: true })) }));
+vi.mock('../promptRunner.js', () => ({
+ runPromptThroughProvider: vi.fn(async () => ({ text: '```html\n<!doctype html><html><canvas></canvas></html>\n```' })),
+}));
+vi.mock('../creativeStyleSources.js', () => ({
+ resolveUniverseStyleSource: vi.fn(async () => null),
+ resolveMoodBoardStyleSource: vi.fn(async () => ({ board: null, images: [] })),
+}));
+const history = vi.hoisted(() => ({ mutateVideoHistory: vi.fn() }));
+vi.mock('../videoGen/history.js', () => history);
+vi.mock('../../lib/ffmpeg.js', async importOriginal => ({
+ ...(await importOriginal()),
+ generateThumbnail: vi.fn(async (_path, id) => `${id}.jpg`),
+ findFfprobe: vi.fn(async () => null),
+}));
+const mux = vi.hoisted(() => ({ installed: false }));
+vi.mock('../pipeline/audioMux.js', () => ({
+ muxVoLines: vi.fn(async (_video, { withInstall }) => withInstall(async () => { mux.installed = true; return { ok: true }; })),
+}));
+
+const { PATHS } = await import('../../lib/paths.js');
+const { createCodeAnimationPackage } = await import('../../lib/codeAnimationPackage.js');
+const { codeAnimationBudgetsSchema } = await import('../../lib/codeAnimationProjects.js');
+const { soundTimeline } = await import('../../lib/codeAnimationSound.js');
+const { acquireBackupSnapshotCut } = await import('../../lib/backupSnapshotBoundary.js');
+const { sourceHashOf, stageProjectFiles, writeRunArtifact } = await import('./projectFiles.js');
+const { startCodeAnimationGeneration } = await import('./index.js');
+const { importProductionPackage } = await import('./projects.js');
+const { startProductionStageRun } = await import('./stages.js');
+const { publishBlenderVideo } = await import('./blenderRender.js');
+const { muxSoundtrack } = await import('./sound.js');
+
+afterAll(() => cleanupTempDataRoots('code-animation-backup-'));
+
+const settle = () => new Promise(resolve => setTimeout(resolve, 50));
+
+/** Each doubled commit reports its name and arguments here before it settles. */
+let hold = null;
+const holdable = (name, result) => async (...args) => {
+ await hold?.(name, ...args);
+ return typeof result === 'function' ? result(...args) : result;
+};
+
+/**
+ * Pause a workflow at the commit `matches` selects, request a cut, and prove
+ * the cut is granted only after that commit settles.
+ */
+async function expectCutDrainsCommit(start, matches) {
+ let reachedCommit;
+ const reached = new Promise(resolve => { reachedCommit = resolve; });
+ let finishCommit;
+ const commitDone = new Promise(resolve => { finishCommit = resolve; });
+ hold = async (...args) => {
+ if (!matches(...args)) return;
+ hold = null;
+ reachedCommit();
+ await commitDone;
+ };
+ const pending = start();
+ await reached;
+ let cutReady = false;
+ const cut = acquireBackupSnapshotCut().then(release => { cutReady = true; return release; });
+ try {
+ await settle();
+ expect(cutReady, 'cut granted while a row naming new bytes was committing').toBe(false);
+ } finally {
+ finishCommit();
+ (await cut)();
+ }
+ return pending;
+}
+
+const manifest = () => ({
+ title: 'Synthetic film', brief: { concept: 'A cube hops over a cone.', cast: '', onScreenText: '' },
+ styleGuide: 'Graphic shapes', renderer: { kind: 'browser', version: 'synthetic-v1', engine: null },
+ format: { width: 1280, height: 720, fps: 12, durationSeconds: 4 }, seed: 1,
+ entrypoints: [{ role: 'preview', path: 'src/index.html' }], assets: [], shots: [], events: [],
+ audio: { kind: 'silence' }, execution: { requested: null, effective: null },
+});
+const pkg = source => createCodeAnimationPackage(manifest(), [{ path: 'src/index.html', content: source }]);
+const PROJECT_ID = 'example-project';
+
+/** A revision whose write-once tree is really staged under the temp data root. */
+async function stagedRevision(source) {
+ const built = pkg(source);
+ const id = randomUUID();
+ const storage = await stageProjectFiles(PROJECT_ID, id, built.files);
+ return {
+ id, packageHash: built.revisionHash, sourceHash: sourceHashOf(built.files),
+ totalBytes: built.files.reduce((sum, file) => sum + Buffer.byteLength(file.content), 0),
+ schemaVersion: built.schemaVersion, manifest: built.manifest,
+ files: built.files.map(({ content: _content, ...file }) => file), storage, createdAt: new Date().toISOString(),
+ };
+}
+
+// A FROZEN film fails inspection, so a run repairs it into a MOVING revision.
+const sample = async (directory, { times, captureTimes = [] }) => {
+ const html = await readFile(join(PATHS.data, directory, 'index.html'), 'utf8');
+ const hash = t => createHash('sha256').update(html.includes('FROZEN') ? 'same' : `t${t}`).digest('hex');
+ return {
+ contract: { durationSec: 4, fps: 12, width: 1280, height: 720 },
+ samples: times.map(t => ({ t, renderHash: hash(t), mean: 80, deviation: 20 })),
+ frames: captureTimes.map(t => ({ t, bytes: Buffer.from(`png-${t}`) })),
+ };
+};
+const repair = async ({ files, entryPath }) => ({
+ files: [{ path: entryPath, content: files.find(file => file.path === entryPath).content.replace('FROZEN', 'MOVING') }], tokens: 1,
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ hold = null;
+ mux.installed = false;
+ const project = { id: PROJECT_ID, budgets: codeAnimationBudgetsSchema.parse({}), localSettings: {} };
+ store.getProjectRecord.mockResolvedValue(project);
+ store.startImportRecord.mockResolvedValue(true);
+ store.commitImportRecord.mockImplementation(holdable('commitImportRecord', project));
+ store.startStageRun.mockResolvedValue();
+ store.saveStageRun.mockImplementation(holdable('saveStageRun'));
+ store.reserveRunBytes.mockResolvedValue(true);
+ store.commitRepairRevision.mockImplementation(holdable('commitRepairRevision', project));
+ jobs.saveCodeAnimationJobRecord.mockImplementation(holdable('saveCodeAnimationJobRecord', job => job));
+ jobs.saveCodeAnimationHtml.mockResolvedValue();
+ history.mutateVideoHistory.mockImplementation(holdable('mutateVideoHistory'));
+});
+
+describe('Code Animation workflows and a backup cut', () => {
+ it('drains a cut behind the completed generation row that names its HTML', async () => {
+ const completed = new Promise(resolve => {
+ jobs.saveCodeAnimationJobRecord.mockImplementation(holdable('saveCodeAnimationJobRecord', job => { if (job.status === 'completed') resolve(); return job; }));
+ });
+ await expectCutDrainsCommit(() => startCodeAnimationGeneration({
+ providerId: 'example-provider', concept: 'A cube hops over a cone.',
+ format: { aspectRatio: '16:9', resolution: '720p', fps: 24, durationSeconds: 4 },
+ }), (name, job) => name === 'saveCodeAnimationJobRecord' && job.status === 'completed');
+ await completed;
+ expect(jobs.saveCodeAnimationHtml).toHaveBeenCalledTimes(1);
+ });
+
+ it('writes no generated HTML while a cut is held', async () => {
+ const release = await acquireBackupSnapshotCut();
+ try {
+ await startCodeAnimationGeneration({
+ providerId: 'example-provider', concept: 'A cube hops over a cone.',
+ format: { aspectRatio: '16:9', resolution: '720p', fps: 24, durationSeconds: 4 },
+ });
+ await settle();
+ expect(jobs.saveCodeAnimationHtml).not.toHaveBeenCalled();
+ } finally {
+ release();
+ }
+ await vi.waitFor(() => expect(jobs.saveCodeAnimationJobRecord).toHaveBeenLastCalledWith(expect.objectContaining({ status: 'completed' })));
+ expect(jobs.saveCodeAnimationHtml).toHaveBeenCalledTimes(1);
+ });
+
+ it('drains a cut behind the revision row that names an imported package tree', async () => {
+ const result = await expectCutDrainsCommit(() => importProductionPackage(PROJECT_ID, pkg('<html><canvas></canvas>MOVING</html>')),
+ name => name === 'commitImportRecord');
+ const [, revision] = store.commitImportRecord.mock.calls[0];
+ expect(result.revision.id).toBe(revision.id);
+ await expect(readFile(join(PATHS.data, revision.storage.relativePath, 'src/index.html'), 'utf8')).resolves.toContain('MOVING');
+ });
+
+ it.each([
+ ['the run row that first names style frames',
+ (name, _id, _status, data) => name === 'saveStageRun' && data.stages.some(stage => stage.key === 'style-frame' && stage.artifacts?.length)],
+ ['the repaired revision row', name => name === 'commitRepairRevision'],
+ ])('drains a cut behind %s', async (_name, matches) => {
+ const revision = await stagedRevision('<html><canvas></canvas>FROZEN</html>');
+ store.getRevisionRecord.mockResolvedValue(revision);
+ const render = vi.fn(async () => ({ jobId: 'media-job', id: 'video-1', filename: 'composition-media-job.mp4' }));
+ let done;
+ await expectCutDrainsCommit(async () => {
+ ({ done } = await startProductionStageRun(PROJECT_ID, { revisionId: revision.id }, { sample, repair, render }));
+ }, matches);
+ await expect(done).resolves.toBe('completed');
+ expect(render).toHaveBeenCalledTimes(1);
+ });
+
+ it('drains a cut behind the history entry that publishes a Blender film', async () => {
+ const source = join(PATHS.data, 'code-animations', 'example-sequence.mp4');
+ await mkdir(join(PATHS.data, 'code-animations'), { recursive: true });
+ await writeFile(source, Buffer.from('mp4'));
+ const published = await publishBlenderVideo(
+ { sequence: { artifact: { relativePath: 'code-animations/example-sequence.mp4' }, geometry: { width: 1280, height: 720 } }, renderer: {}, artifacts: [] },
+ { revision: { id: 'rev', sourceHash: 'hash', manifest: manifest() }, reserve: async () => {} },
+ );
+ await expectCutDrainsCommit(() => published.commit(), name => name === 'mutateVideoHistory');
+ await expect(readFile(join(PATHS.videos, published.filename), 'utf8')).resolves.toBe('mp4');
+ });
+
+ it('installs a muxed soundtrack over a published film only outside a cut', async () => {
+ const runId = randomUUID();
+ const revision = { id: randomUUID(), packageHash: 'pkg', manifest: { ...manifest(), audio: { kind: 'procedural', version: 1, events: [] } } };
+ const name = `sound-${revision.id}.wav`;
+ const artifact = await writeRunArtifact(PROJECT_ID, runId, name, Buffer.alloc(64, 1));
+ await mkdir(PATHS.videos, { recursive: true });
+ await writeFile(join(PATHS.videos, 'example-film.mp4'), Buffer.from('mp4'));
+ const soundtrack = {
+ kind: 'procedural', revisionId: revision.id, packageHash: 'pkg', timelineHash: soundTimeline(revision.manifest).hash,
+ timeline: soundTimeline(revision.manifest), artifact: { ...artifact, runId, name },
+ };
+ const release = await acquireBackupSnapshotCut();
+ let pending;
+ try {
+ pending = muxSoundtrack({ projectId: PROJECT_ID, revision, soundtrack, result: { filename: 'example-film.mp4' }, signal: new AbortController().signal });
+ await settle();
+ expect(mux.installed).toBe(false);
+ } finally {
+ release();
+ }
+ // The doubled ffprobe is absent, so verification refuses after the install.
+ await expect(pending).rejects.toMatchObject({ code: 'CODE_ANIMATION_SOUND_UNVERIFIED' });
+ expect(mux.installed).toBe(true);
+ });
+});
diff --git a/server/services/codeAnimation/blenderRender.js b/server/services/codeAnimation/blenderRender.js
index b2011ae5ea..ab37a34243 100644
--- a/server/services/codeAnimation/blenderRender.js
+++ b/server/services/codeAnimation/blenderRender.js
@@ -8,6 +8,7 @@ import { ServerError } from '../../lib/errorHandler.js';
import { findFfmpeg, runFfmpegProcess, H264_ENCODE_ARGS, BT709_CONTAINER_ARGS, bt709TagFilter,
probeVideoGeometry, probeFrameCount, generateThumbnail } from '../../lib/ffmpeg.js';
import { mutateVideoHistory } from '../videoGen/history.js';
+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
import { writeRunArtifact } from './projectFiles.js';
import { resolveBlenderExecution } from './execution.js';
import { BLENDER_DRIVER } from './blenderDriver.js';
@@ -132,12 +133,14 @@ export async function publishBlenderVideo(sequence, { revision, signal, reserve
thumbnail = await generateThumbnail(destination, id);
if (!thumbnail) throw fail('Blender thumbnail generation failed');
signal?.throwIfAborted();
- const commit = () => mutateVideoHistory(history => {
+ // The history entry first names the copied MP4 and its poster, so it
+ // commits under the backup lease (#9982).
+ const commit = () => withBackupAssetPublication(() => mutateVideoHistory(history => {
history.unshift({ id, filename, thumbnail, modelId: 'code-animation-blender', prompt: revision.manifest.title,
...sequence.sequence.geometry, seed: revision.manifest.seed ?? 0, createdAt: new Date().toISOString(),
codeAnimation: { revisionId: revision.id, sourceHash: revision.sourceHash, renderer: sequence.renderer } });
return history;
- });
+ }));
success = true;
return { id, filename, thumbnail, path: `/data/videos/${filename}`, renderer: sequence.renderer, artifacts: sequence.artifacts,
commit, cleanup: async () => { await rm(destination, { force: true }); await rm(join(PATHS.videoThumbnails, thumbnail), { force: true }); } };
diff --git a/server/services/codeAnimation/index.js b/server/services/codeAnimation/index.js
index 7651b8b415..a4e6a50375 100644
--- a/server/services/codeAnimation/index.js
+++ b/server/services/codeAnimation/index.js
@@ -20,6 +20,7 @@ import { makePathResolver } from '../../lib/pathSafety.js';
import { isNonBlankStr, trimTo } from '../../lib/textUtils.js';
import { UPLOAD_AUDIO_EXTENSIONS } from '../../lib/mimeTypes.js';
import { normalizeWaveSketch } from '../../lib/waveSketch.js';
+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
import { SUPPORTED_AUDIO_EXTENSIONS } from '../pipeline/musicLibrary.js';
import { resolveMoodBoardStyleSource as resolveMoodBoard, resolveUniverseStyleSource as resolveUniverse } from '../creativeStyleSources.js';
import {
@@ -456,16 +457,21 @@ export async function startCodeAnimationGeneration(input) {
console.log(`🎞️ Code animation generation ${id.slice(0, 8)} started on ${provider.id}`);
runGeneration({ provider, model: input.model, effort: input.effort, prompt: built.prompt, referencePaths: built.referencePaths })
.then(async ({ html, provider: ranOn, model, runId }) => {
- await saveCodeAnimationHtml(id, html);
- const completedAt = new Date().toISOString();
- await saveCodeAnimationJobRecord({
- ...job,
- status: 'completed',
- providerId: ranOn,
- model,
- runId,
- completedAt,
- updatedAt: completedAt,
+ // The HTML file and the completed row that first names it are one
+ // backup-admitted workflow (#9982), so a snapshot never dumps a
+ // completed job whose file its copy missed.
+ await withBackupAssetPublication(async () => {
+ await saveCodeAnimationHtml(id, html);
+ const completedAt = new Date().toISOString();
+ await saveCodeAnimationJobRecord({
+ ...job,
+ status: 'completed',
+ providerId: ranOn,
+ model,
+ runId,
+ completedAt,
+ updatedAt: completedAt,
+ });
});
emitCodeAnimationChanged(id);
activeJobs.delete(id);
diff --git a/server/services/codeAnimation/projects.js b/server/services/codeAnimation/projects.js
index 49ff6fd2a9..0418d91074 100644
--- a/server/services/codeAnimation/projects.js
+++ b/server/services/codeAnimation/projects.js
@@ -4,6 +4,7 @@ import { codeAnimationPackageSchema, summarizeCodeAnimationPackage } from '../..
import { codeAnimationProjectSchema, codeAnimationProjectPatchSchema } from '../../lib/codeAnimationProjects.js';
import { validateRequest } from '../../lib/validation.js';
import { ServerError } from '../../lib/errorHandler.js';
+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
import { emitCodeAnimationChanged } from '../socket.js';
import * as store from './projectStore.js';
import { stageProjectFiles, readProjectFiles, sourceHashOf, ownedStorageRetained } from './projectFiles.js';
@@ -63,7 +64,9 @@ export async function importProductionPackage(projectId, input) {
files: pkg.files.map(({ content: _content, ...file }) => file),
storage, createdAt: new Date().toISOString(),
};
- const saved = await store.commitImportRecord(projectId, revision, runId);
+ // The revision row first names the write-once tree staged above, so it
+ // commits under the backup lease (#9982).
+ const saved = await withBackupAssetPublication(() => store.commitImportRecord(projectId, revision, runId));
emitCodeAnimationChanged(projectId);
return { project: saved, revision, runId, executed: false };
} catch (error) {
diff --git a/server/services/codeAnimation/sound.js b/server/services/codeAnimation/sound.js
index 361d22309d..d73ca12a8f 100644
--- a/server/services/codeAnimation/sound.js
+++ b/server/services/codeAnimation/sound.js
@@ -13,6 +13,7 @@ import { pcmToWavBuffer } from '../../lib/chiptuneRender.js';
import { measureWavAudio } from '../../lib/wavAudioFile.js';
import { CODE_ANIMATION_SAMPLE_RATE, measureSoundEvents, soundHash, soundTimeline, synthesizeSoundtrack } from '../../lib/codeAnimationSound.js';
import { muxVoLines } from '../pipeline/audioMux.js';
+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
import { readRunArtifact, writeRunArtifact } from './projectFiles.js';
const exec = promisify(execFile);
@@ -95,7 +96,10 @@ export async function muxSoundtrack({ projectId, revision, soundtrack, result, s
signal.throwIfAborted();
// Account for the newly rendered candidate and the second-pass mux scratch.
if (reserve) await reserve((await stat(videoPath)).size * 2 + soundtrack.artifact.bytes);
- const mux = await muxVoLines(videoPath, { voLines: [{ path: audioPath, offsetSec: 0 }], signal });
+ // A browser render's MP4 is already named by its history entry, so the
+ // in-place install of the muxed file takes the backup lease (#9982).
+ const mux = await muxVoLines(videoPath, { voLines: [{ path: audioPath, offsetSec: 0 }], signal,
+ withInstall: install => withBackupAssetPublication(install) });
if (!mux.ok) throw fail(`Soundtrack mux failed: ${mux.reason}`);
signal.throwIfAborted();
const probe = await findFfprobe();
diff --git a/server/services/codeAnimation/stages.js b/server/services/codeAnimation/stages.js
index 091262b693..f7ac0c6f9c 100644
--- a/server/services/codeAnimation/stages.js
+++ b/server/services/codeAnimation/stages.js
@@ -18,6 +18,7 @@ import { codeAnimationStageRunSchema } from '../../lib/codeAnimationProjects.js'
import { ServerError } from '../../lib/errorHandler.js';
import { extractJson } from '../../lib/jsonExtract.js';
import { PATHS } from '../../lib/paths.js';
+import { withBackupAssetPublication } from '../../lib/backupSnapshotBoundary.js';
import { htmlCompositionContractSchema, validateRequest } from '../../lib/validation.js';
import { emitCodeAnimationChanged } from '../socket.js';
import { analyzeEvidence, evaluateVerdict } from './evidence.js';
@@ -71,7 +72,10 @@ function snapshot(ctx) {
async function persist(ctx, status = 'running', { completed = false, revisionId = null } = {}) {
ctx.state.spent.elapsedMs = Date.now() - ctx.startedAt + ctx.state.spent.priorElapsedMs;
- await store.saveStageRun(ctx.runId, status, snapshot(ctx), { completed, revisionId });
+ // The run row first names the write-once run artifacts (frames, soundtrack,
+ // scene bake) and the published output, so it commits under the backup
+ // lease (#9982): a cut copies files before it dumps rows.
+ await withBackupAssetPublication(() => store.saveStageRun(ctx.runId, status, snapshot(ctx), { completed, revisionId }));
emitCodeAnimationChanged(ctx.projectId);
}
@@ -347,7 +351,8 @@ async function repairStage(ctx, revision, findings) {
files: pkg.files.map(({ content: _content, ...file }) => file), storage, createdAt: iso(),
parentRevisionId: revision.id, repair: { runId: ctx.runId, stageRunId: entry.stageRunId, intent },
};
- await store.commitRepairRevision(ctx.projectId, created);
+ // The repaired revision row first names the tree staged above (#9982).
+ await withBackupAssetPublication(() => store.commitRepairRevision(ctx.projectId, created));
ctx.state.repairs.push({ revisionId: id, fromRevisionId: revision.id, sourceHash, findingKinds: intent.findingKinds, tokens: out.tokens || 0 });
ctx.state.currentRevisionId = id;
return { intent, toRevisionId: id, toSourceHash: sourceHash };
diff --git a/server/services/pipeline/audioMux.js b/server/services/pipeline/audioMux.js
index 862a1d3930..2d1ac541e5 100644
--- a/server/services/pipeline/audioMux.js
+++ b/server/services/pipeline/audioMux.js
@@ -271,8 +271,12 @@ export function buildVoMuxArgs({ inputVideoPath, voLines, musicPath, musicGain =
* finite, >= 0 offset are dropped (un-placed lines stay silent rather than
* stacking at t=0). With no usable lines this returns ok:false so the caller
* can fall back to the music-only `muxMusicBed` path.
+ *
+ * `withInstall` wraps only the in-place install of the encoded file, so a
+ * caller whose video a record already names can hold the backup admission
+ * lease across that replacement without holding it through the encode.
*/
-export async function muxVoLines(inputVideoPath, { voLines = [], musicPath = null, musicGain = DEFAULT_MUSIC_GAIN, duck = DEFAULT_DUCK, signal } = {}) {
+export async function muxVoLines(inputVideoPath, { voLines = [], musicPath = null, musicGain = DEFAULT_MUSIC_GAIN, duck = DEFAULT_DUCK, signal, withInstall = install => install() } = {}) {
if (!inputVideoPath || !existsSync(inputVideoPath)) {
return { ok: false, reason: 'input video missing' };
}
@@ -302,7 +306,7 @@ export async function muxVoLines(inputVideoPath, { voLines = [], musicPath = nul
await unlink(tmpOut).catch(() => {});
return result;
}
- const installed = await installEncodedVideo(tmpOut, inputVideoPath, 'VO mux');
+ const installed = await withInstall(() => installEncodedVideo(tmpOut, inputVideoPath, 'VO mux'));
if (!installed.ok) return installed;
return { ok: true, lineCount: placed.length, ducked: !!usableMusic, clipAudio };
}