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: re-check a Music Video render mark under the write lock before boot recovery demotes it (#9010)

[._.]/ Adam Eivy9e22261d5272
diff --git a/server/services/musicVideo/excerptRender.js b/server/services/musicVideo/excerptRender.js
index 3652c85fc3..6f6e9882d1 100644
--- a/server/services/musicVideo/excerptRender.js
+++ b/server/services/musicVideo/excerptRender.js
@@ -323,21 +323,28 @@ export async function recoverStuckMusicVideoExcerpts() {
const stuck = (project.excerpts || []).filter((e) => e.status === 'rendering'
&& !projectExcerptRenders.has(project.id) && isLocalRenderMark(e.renderingOn, instanceId));
if (stuck.length === 0) continue;
- const ok = await mutateProjectRecord(project.id, (current) => {
+ // Re-checked against the FRESHEST record under the write lock: a peer sync
+ // landing after the list may have finished the draft or handed it to
+ // another instance, and only a still-stuck local mark is demoted.
+ const stuckIds = new Set(stuck.map((e) => e.id));
+ const outcome = await mutateProjectRecord(project.id, (current) => {
+ const demoted = (current.excerpts || []).filter((e) => stuckIds.has(e.id) && e.status === 'rendering'
+ && !projectExcerptRenders.has(project.id) && isLocalRenderMark(e.renderingOn, instanceId));
let next = current;
- for (const excerpt of stuck) {
+ for (const excerpt of demoted) {
next = { ...next, excerpts: (next.excerpts || []).map((e) => (e.id === excerpt.id ? { ...e, status: 'error', error: 'Interrupted by a server restart', jobId: null, partialFilename: null, renderingOn: null } : e)) };
next = settleRevisionRender(next, excerpt.id, { status: 'error', error: 'The draft render was interrupted by a server restart' });
}
- return { project: next };
- }).then(() => { recovered += stuck.length; return true; }, (err) => {
+ return { project: next, demoted };
+ }).catch((err) => {
console.error(`❌ Music Video excerpt recovery: project ${project.id.slice(0, 8)} write failed: ${err.message}`);
- return false;
+ return null;
});
// Only once the record no longer points at them, so a failed write can't
// leave a record naming a file that is gone.
- if (!ok) continue;
- for (const { partialFilename } of stuck) {
+ if (!outcome) continue;
+ recovered += outcome.demoted.length;
+ for (const { partialFilename } of outcome.demoted) {
if (typeof partialFilename !== 'string' || !partialFilename) continue;
await unlinkUnder(PATHS.videos, partialFilename);
await unlinkUnder(PATHS.videoThumbnails, sheetFilenameFor(partialFilename));
diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.js
index a69b2bda61..ddc9db25e4 100644
--- a/server/services/musicVideo/render.js
+++ b/server/services/musicVideo/render.js
@@ -34,7 +34,8 @@ import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { attachFfmpegRenderGuard } from '../../lib/ffmpegRenderGuard.js';
import { loadHistory, mutateVideoHistory } from '../videoGen/local.js';
import { getTrack } from '../tracks/index.js';
-import { getProject, listProjects, updateProject } from './projects.js';
+import { getProject, listProjects, updateProject, mutateProjectRecord } from './projects.js';
+import { applyProjectPatch } from './projectsLogic.js';
import { sceneHasAuthoredSpan, sceneVisualLayer } from '../../lib/musicVideoLayers.js';
import { renderableCues, sectionCardCues } from './composition.js';
import { renderTypographyOverlays, removeCompositionScratch, sweepCompositionScratch } from './compositionRender.js';
@@ -805,24 +806,37 @@ export async function recoverStuckMusicVideoRenders() {
const instanceId = await ensureInstanceId();
const stuck = (await listProjects()).filter((p) => p?.status === 'rendering'
&& !projectRenders.has(p.id) && isLocalRenderMark(p.renderingOn, instanceId));
- // A render whose history append landed but whose 'complete' write failed
- // still names its (finished) file — that file is the gallery's, not a partial.
- const finished = stuck.some((p) => p.renderPartialFilename)
- ? new Set((await loadHistory()).map((entry) => entry?.filename))
- : new Set();
+ // Filenames the video history references, loaded on first need: a render
+ // whose history append landed but whose 'complete' write failed still names
+ // its (finished) file — that file is the gallery's, not a partial.
+ let finished = null;
let recovered = 0;
for (const project of stuck) {
- const targetStatus = project.renderHistoryId ? 'complete' : 'ready';
- const ok = await updateProject(project.id, settledRender(targetStatus)).then(() => true, (err) => {
- console.error(`❌ Music Video recovery: project ${project.id.slice(0, 8)} status→${targetStatus} write failed: ${err.message}`);
- return false;
+ // Re-checked against the FRESHEST record under the write lock: a peer sync
+ // landing between the list and this write may have handed the mark to
+ // another instance (or finished it), and that render is not ours to demote.
+ const outcome = await mutateProjectRecord(project.id, (current) => {
+ const stillStuck = current?.status === 'rendering' && !projectRenders.has(current.id)
+ && isLocalRenderMark(current.renderingOn, instanceId);
+ if (!stillStuck) return { project: current, demoted: false };
+ const targetStatus = current.renderHistoryId ? 'complete' : 'ready';
+ return { project: applyProjectPatch(current, settledRender(targetStatus)), demoted: true, partial: current.renderPartialFilename };
+ }).catch((err) => {
+ console.error(`❌ Music Video recovery: project ${project.id.slice(0, 8)} demotion write failed: ${err.message}`);
+ return null;
});
- if (!ok) continue;
+ if (!outcome?.demoted) continue;
recovered++;
// Only once the record no longer points at it. The filename came off a
// (possibly peer-synced) record, so it is only resolved inside videos/.
- const partial = project.renderPartialFilename;
- const partialPath = typeof partial === 'string' && !finished.has(partial) ? safeUnder(PATHS.videos, partial) : null;
+ const { partial } = outcome;
+ if (typeof partial !== 'string' || !partial) continue;
+ // An unreadable history keeps every file — a stray partial beats deleting a finished render.
+ finished ??= await loadHistory().then((history) => new Set(history.map((entry) => entry?.filename)), (err) => {
+ console.warn(`⚠️ Music Video recovery: video history unreadable, keeping partial render output: ${err.message}`);
+ return false;
+ });
+ const partialPath = !finished || finished.has(partial) ? null : safeUnder(PATHS.videos, partial);
if (partialPath) await unlink(partialPath).catch(() => {});
}
if (stuck.length > 0) console.log(`🎬 Music Video boot recovery: demoted ${recovered}/${stuck.length} stuck render(s)`);
diff --git a/server/services/musicVideo/render.terminal.test.js b/server/services/musicVideo/render.terminal.test.js
index ae6ffcae2d..61239f871e 100644
--- a/server/services/musicVideo/render.terminal.test.js
+++ b/server/services/musicVideo/render.terminal.test.js
@@ -216,14 +216,27 @@ describe('status write failures are logged, not swallowed (#8430)', () => {
});
});
+// Recovery re-checks each record under the store's write lock (#9010): back
+// both the list and the transform with one in-memory store.
+const seedStore = (records) => {
+ const store = new Map(records.map((r) => [r.id, r]));
+ listProjects.mockResolvedValueOnce(records);
+ mutateProjectRecord.mockImplementation(async (id, transform) => {
+ const outcome = transform(store.get(id));
+ store.set(id, outcome.project);
+ return outcome;
+ });
+ return store;
+};
+const statusOf = (store) => Object.fromEntries([...store].map(([id, p]) => [id, p.status]));
+
describe('recoverStuckMusicVideoRenders (#8430)', () => {
it('demotes stale renders by history, skips live jobs and other statuses', async () => {
const { recoverStuckMusicVideoRenders } = await import('./render.js');
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
prime('live-1');
await renderMusicVideo('live-1');
- updateProject.mockClear();
- listProjects.mockResolvedValueOnce([
+ const store = seedStore([
{ id: 'done-1', status: 'rendering', renderHistoryId: 'hist-1' },
{ id: 'fresh-1', status: 'rendering' },
{ id: 'live-1', status: 'rendering' },
@@ -232,10 +245,8 @@ describe('recoverStuckMusicVideoRenders (#8430)', () => {
await recoverStuckMusicVideoRenders();
- expect(updateProject.mock.calls).toEqual([
- ['done-1', settled('complete')],
- ['fresh-1', settled('ready')],
- ]);
+ expect(statusOf(store)).toEqual({ 'done-1': 'complete', 'fresh-1': 'ready', 'live-1': 'rendering', 'idle-1': 'ready' });
+ expect(store.get('fresh-1')).toMatchObject({ renderingOn: null, renderPartialFilename: null });
expect(logSpy.mock.calls.some(([line]) => line.includes('demoted 2/2'))).toBe(true);
logSpy.mockRestore();
});
@@ -252,22 +263,27 @@ describe('recoverStuckMusicVideoRenders (#8430)', () => {
const { recoverStuckMusicVideoRenders } = await import('./render.js');
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
loadHistory.mockResolvedValue([{ id: 'r-done', filename: 'music-video-finished.mp4' }]);
- listProjects.mockResolvedValueOnce([
+ const store = seedStore([
{ id: 'mine-1', status: 'rendering', renderingOn: 'inst-self', renderPartialFilename: 'music-video-mine.mp4' },
{ id: 'peer-1', status: 'rendering', renderingOn: 'inst-peer', renderPartialFilename: 'music-video-peer.mp4' },
{ id: 'legacy-1', status: 'rendering' },
// Its history append landed but the 'complete' write did not: the file is a finished render.
{ id: 'late-1', status: 'rendering', renderingOn: 'inst-self', renderPartialFilename: 'music-video-finished.mp4' },
+ // Listed as ours, but a peer sync handed the mark over before the demotion write.
+ { id: 'moved-1', status: 'rendering', renderingOn: 'inst-self', renderPartialFilename: 'music-video-moved.mp4' },
]);
+ const listed = mutateProjectRecord.getMockImplementation();
+ mutateProjectRecord.mockImplementation(async (id, transform) => {
+ if (id === 'moved-1') store.set(id, { ...store.get(id), renderingOn: 'inst-peer' });
+ return listed(id, transform);
+ });
await recoverStuckMusicVideoRenders();
- expect(updateProject.mock.calls).toEqual([
- ['mine-1', settled('ready')],
- ['legacy-1', settled('ready')],
- ['late-1', settled('ready')],
- ]);
+ expect(statusOf(store)).toEqual({ 'mine-1': 'ready', 'peer-1': 'rendering', 'legacy-1': 'ready', 'late-1': 'ready', 'moved-1': 'rendering' });
+ expect(store.get('peer-1')).toMatchObject({ renderingOn: 'inst-peer', renderPartialFilename: 'music-video-peer.mp4' });
expect(unlink.mock.calls).toEqual([['/data/videos/music-video-mine.mp4']]);
+ expect(logSpy.mock.calls.some(([line]) => line.includes('demoted 3/4'))).toBe(true);
logSpy.mockRestore();
});
@@ -275,21 +291,20 @@ describe('recoverStuckMusicVideoRenders (#8430)', () => {
const { recoverStuckMusicVideoExcerpts } = await import('./excerptRender.js');
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
const draft = (id, extra) => ({ id, status: 'rendering', jobId: id, partialFilename: `${id}.mp4`, notes: [], ...extra });
- let record = {
+ const store = seedStore([{
id: 'mv-x', status: 'complete', revisions: [],
excerpts: [draft('mve-mine', { renderingOn: 'inst-self' }), draft('mve-peer', { renderingOn: 'inst-peer' }), draft('mve-legacy')],
- };
- listProjects.mockResolvedValueOnce([record]);
- mutateProjectRecord.mockImplementation(async (_id, transform) => { record = transform(record).project; return {}; });
+ }]);
await recoverStuckMusicVideoExcerpts();
- const byId = Object.fromEntries(record.excerpts.map((e) => [e.id, e]));
+ const byId = Object.fromEntries(store.get('mv-x').excerpts.map((e) => [e.id, e]));
expect(byId['mve-mine']).toMatchObject({ status: 'error', renderingOn: null, partialFilename: null });
expect(byId['mve-legacy']).toMatchObject({ status: 'error', partialFilename: null });
expect(byId['mve-peer']).toMatchObject({ status: 'rendering', renderingOn: 'inst-peer', partialFilename: 'mve-peer.mp4' });
- expect(unlink.mock.calls.map(([p]) => p)).not.toContain('/data/videos/mve-peer.mp4');
- expect(unlink.mock.calls.map(([p]) => p)).toContain('/data/videos/mve-mine.mp4');
+ const unlinked = unlink.mock.calls.map(([p]) => p);
+ expect(unlinked).toContain('/data/videos/mve-mine.mp4');
+ expect(unlinked).not.toContain('/data/videos/mve-peer.mp4');
logSpy.mockRestore();
});
@@ -297,22 +312,26 @@ describe('recoverStuckMusicVideoRenders (#8430)', () => {
const { recoverStuckMusicVideoRenders } = await import('./render.js');
listProjects.mockRejectedValueOnce(new Error('DB unavailable'));
await expect(recoverStuckMusicVideoRenders()).rejects.toThrow('DB unavailable');
- expect(updateProject).not.toHaveBeenCalled();
+ expect(mutateProjectRecord).not.toHaveBeenCalled();
});
it('logs a failed demotion and keeps recovering the rest', async () => {
const { recoverStuckMusicVideoRenders } = await import('./render.js');
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
- listProjects.mockResolvedValueOnce([
+ const store = seedStore([
{ id: 'bad-1', status: 'rendering' },
{ id: 'good-1', status: 'rendering' },
]);
- updateProject.mockRejectedValueOnce(new Error('write failed'));
+ const listed = mutateProjectRecord.getMockImplementation();
+ mutateProjectRecord.mockImplementation(async (id, transform) => {
+ if (id === 'bad-1') throw new Error('write failed');
+ return listed(id, transform);
+ });
await recoverStuckMusicVideoRenders();
- expect(updateProject).toHaveBeenCalledWith('good-1', settled('ready'));
+ expect(statusOf(store)).toEqual({ 'bad-1': 'rendering', 'good-1': 'ready' });
expect(errorSpy.mock.calls.some(([line]) => line.includes('bad-1'))).toBe(true);
expect(logSpy.mock.calls.some(([line]) => line.includes('demoted 1/2'))).toBe(true);
errorSpy.mockRestore();