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: save media outcomes before acknowledging them (#9737)

Adam Eivyb98f72134489
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index 4a4c6b9a69..f1e6be966a 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -446,6 +446,7 @@ export function listQueueJobs({ kind, owner, limit = 10 } = {}) {
...cloudRunning,
...remoteRunning,
...queue,
+ ...archive.filter((job) => job.durabilityPending),
].filter(matches);
const recent = [];
const finishedAt = (job) => new Date(job.completedAt || job.startedAt || job.queuedAt || 0).getTime();
@@ -467,19 +468,45 @@ export function listQueueJobs({ kind, owner, limit = 10 } = {}) {
// (e.g. completed→running). Chaining ensures every snapshot reflects the
// state at its enqueue time, in submission order.
let persistChain = Promise.resolve();
+// Terminal outcomes stay private until the snapshot containing them succeeds.
+// Recovery commits storage only; it never invokes a generator again.
+const pendingTransitions = new Map();
+function stageTerminalTransition(job, apply, acknowledge) {
+ job.terminating = true;
+ const target = { ...job };
+ apply(target);
+ job.durabilityPending = { status: target.status, result: target.result, error: target.error,
+ completedAt: target.completedAt, progress: target.progress, statusMsg: target.statusMsg, videoFailure: target.videoFailure };
+ pendingTransitions.set(job, acknowledge);
+}
+async function persistTerminalTransition(job) {
+ for (let attempt = 0; attempt < 3; attempt += 1) {
+ try {
+ await persist();
+ return;
+ } catch (error) {
+ job.persistenceError = true;
+ mediaJobEvents.emit('changed', {});
+ if (attempt === 2) {
+ throw new ServerError('Media outcome is awaiting storage recovery; restore writable storage and flush the queue', {
+ status: 503, code: MEDIA_QUEUE_PERSIST_FAILED,
+ });
+ }
+ }
+ }
+}
// Set when the boot read of JOBS_FILE was untrustworthy (#4115). Every persist()
// writes the FULL in-memory snapshot, so persisting on top of a queue we failed
// to restore would replace the real jobs file with whatever this process happens
// to hold — the classic "unreadable read becomes an empty write". Latching the
-// writer off preserves the file for the user to recover or delete; the queue
-// still runs normally in memory for the life of the process.
+// writer off preserves the file for the user to recover or delete. Admission
+// and dispatch stay disabled because no transition can be made durable.
let persistBlocked = false;
function persist() {
- // Blocked: nothing is written, but callers awaiting durability (enqueueJob)
- // must not inherit a stale rejection from a write that predates the latch.
+ // A blocked writer cannot satisfy admission or transition durability.
if (persistBlocked) {
mediaJobEvents.emit('changed', {});
- return persistChain.catch(() => {});
+ return Promise.reject(new Error('Media queue storage is blocked until its snapshot is repaired and the server restarts'));
}
// Every queue mutation, including holds, deletion and debounced progress,
// converges here. Invalidate after the write settles so readers see the final
@@ -491,12 +518,13 @@ function persist() {
}
async function persistImpl() {
const cutoff = Date.now() - COMPLETED_TTL_MS;
+ const pendingArchive = archive.filter((job) => job.durabilityPending);
const trimmedArchive = archive
.filter((j) => {
const ts = j.completedAt ? new Date(j.completedAt).getTime() : Date.now();
- return ts > cutoff;
+ return !j.durabilityPending && ts > cutoff;
})
- .slice(-MAX_PERSISTED_ARCHIVE);
+ .slice(-MAX_PERSISTED_ARCHIVE).concat(pendingArchive);
// Mutate `archive` in place so subsequent reads see the trim too.
archive.length = 0;
archive.push(...trimmedArchive);
@@ -508,10 +536,19 @@ async function persistImpl() {
...archive,
];
// Strip non-serializable bits.
- const serializable = live.map(({ id, kind, owner, status, queuedAt, startedAt, completedAt, params, result, error, position, progress, statusMsg, etaMs }) =>
+ const serializable = live.map((job) => ({ ...job, ...job.durabilityPending })).map(({ id, kind, owner, status, queuedAt, startedAt, completedAt, params, result, error, position, progress, statusMsg, etaMs }) =>
({ id, kind, owner, status, queuedAt, startedAt, completedAt, params, result, error, position, progress, statusMsg, etaMs }),
);
+ const transitions = [...pendingTransitions];
await atomicWrite(JOBS_FILE, { jobs: serializable, videoHolds: videoHolds.snapshot() });
+ for (const [job, acknowledge] of transitions) {
+ if (pendingTransitions.get(job) !== acknowledge) continue;
+ pendingTransitions.delete(job);
+ Object.assign(job, job.durabilityPending);
+ delete job.durabilityPending;
+ delete job.persistenceError;
+ await acknowledge();
+ }
}
export async function initMediaJobQueue() {
@@ -679,8 +716,10 @@ export async function initMediaJobQueue() {
const entry = ensureSseEntry(j.id);
broadcastSse(entry, { type: 'queued', position: j.position });
}
- await persist();
- startWorker();
+ if (!persistBlocked) {
+ await persist();
+ startWorker();
+ }
})();
return initPromise;
}
@@ -727,35 +766,10 @@ function startLaneJob(job, { lane }) {
const label = lane === 'cloud'
? (job.params?.mode || 'cloud')
: lane === 'remote' ? `remote ${job.kind}` : job.kind;
- persist().catch((e) => console.log(`⚠️ mediaJobQueue persist on ${label} start failed: ${e.message}`));
- broadcastSse(ensureSseEntry(job.id), { type: 'started', kind: job.kind });
- mediaJobEvents.emit('started', job);
- console.log(`▶️ media-job [${job.id.slice(0, 8)}] ${label} started`);
- (async () => {
- try {
- await runJob(job);
- } catch (err) {
- // runJob threw before its own terminal handlers ran (e.g. PYTHON
- // not configured). Recover so a single bad job can't freeze its lane.
- console.error(`❌ media-job [${job.id.slice(0, 8)}] ${label} runJob threw: ${err.message}`, err.stack || '');
- if (job.status === 'running') {
- job.status = job.cancelRequested ? 'canceled' : 'failed';
- videoHolds.captureFailure(job, err);
- // A ServerError carries a message the gen module wrote FOR the user, so
- // surface it verbatim — every media surface renders `job.error`, and the
- // "runJob threw:" prefix turned an actionable refusal into developer
- // noise. Anything else is an unexpected crash and keeps the prefix so
- // the origin stays obvious.
- job.error = job.cancelRequested
- ? 'Canceled'
- : err instanceof ServerError ? err.message : `runJob threw: ${err.message}`;
- job.completedAt = new Date().toISOString();
- broadcastSse(ensureSseEntry(job.id), job.cancelRequested
- ? { type: 'canceled', reason: job.error } : { type: 'error', error: job.error });
- closeJobAfterDelay(sseJobs, job.id);
- mediaJobEvents.emit(job.status, job);
- }
- }
+ let finalized = false;
+ function finalizeLane() {
+ if (finalized) return;
+ finalized = true;
// Count once, after every terminal path (including pre-dispatch throws),
// and before releasing the lane. Boot reconciliation never comes here.
videoHolds.recordTerminal(job);
@@ -775,7 +789,43 @@ function startLaneJob(job, { lane }) {
archive.push(job);
recomputeQueuePositions();
persist().catch((e) => console.log(`⚠️ mediaJobQueue persist on ${label} done failed: ${e.message}`));
- })();
+ }
+ let markRunning;
+ trackOperation(dispatchOperations, new Promise((resolve) => { markRunning = resolve; }));
+ (async () => {
+ try {
+ await persist();
+ // Cancellation can win while the running snapshot is blocked.
+ if (job.cancelRequested && !isRemoteMediaJob(job)) throw new ServerError('Canceled before provider start');
+ broadcastSse(ensureSseEntry(job.id), { type: 'started', kind: job.kind });
+ mediaJobEvents.emit('started', job);
+ console.log(`▶️ media-job [${job.id.slice(0, 8)}] ${label} started`);
+ const lifecycle = runJob(job);
+ markRunning();
+ await lifecycle;
+ } catch (err) {
+ markRunning();
+ // runJob threw before its own terminal handlers ran (e.g. PYTHON
+ // not configured). Recover so a single bad job can't freeze its lane.
+ console.error(`❌ media-job [${job.id.slice(0, 8)}] ${label} runJob threw: ${err.message}`, err.stack || '');
+ if (job.status === 'running') {
+ stageTerminalTransition(job, (j) => {
+ j.status = j.cancelRequested ? 'canceled' : 'failed';
+ videoHolds.captureFailure(j, err);
+ j.error = j.cancelRequested ? 'Canceled' : err instanceof ServerError ? err.message : `runJob threw: ${err.message}`;
+ j.completedAt = new Date().toISOString();
+ }, () => {
+ broadcastSse(ensureSseEntry(job.id), job.cancelRequested
+ ? { type: 'canceled', reason: job.error } : { type: 'error', error: job.error });
+ closeJobAfterDelay(sseJobs, job.id);
+ mediaJobEvents.emit(job.status, job);
+ finalizeLane();
+ });
+ await trackTerminalOperation(persistTerminalTransition(job));
+ }
+ }
+ finalizeLane();
+ })().catch((error) => console.error(`❌ media-job [${job.id.slice(0, 8)}] storage settlement pending: ${error.message}`));
return true;
}
@@ -786,25 +836,24 @@ async function settleQueuedJob(job, { status, error }) {
const idx = queue.indexOf(job);
if (idx < 0 || job.status !== 'queued') return false;
queue.splice(idx, 1);
- job.status = status;
- job.error = error;
- job.completedAt = new Date().toISOString();
+ stageTerminalTransition(job, (j) => {
+ j.status = status;
+ j.error = error;
+ j.completedAt = new Date().toISOString();
+ }, () => {
+ trackTerminalOperation((async () => {
+ await safeUnlinkUpload(job.params?.uploadedTempPath);
+ await safeUnlinkUpload(job.params?.audioFilePath);
+ for (const p of normalizeTempPaths(job.params?.uploadedTempPaths)) await safeUnlinkUpload(p);
+ broadcastSse(ensureSseEntry(job.id), status === 'canceled'
+ ? { type: 'canceled', reason: error } : { type: 'error', error });
+ closeJobAfterDelay(sseJobs, job.id);
+ mediaJobEvents.emit(status, job);
+ })());
+ });
archive.push(job);
recomputeQueuePositions();
- await trackTerminalOperation((async () => {
- await safeUnlinkUpload(job.params?.uploadedTempPath);
- await safeUnlinkUpload(job.params?.audioFilePath);
- for (const p of normalizeTempPaths(job.params?.uploadedTempPaths)) {
- await safeUnlinkUpload(p);
- }
- await persist().catch((e) => console.error(`❌ mediaJobQueue persist on queued ${status} failed: ${e.message}`));
- broadcastSse(ensureSseEntry(job.id), status === 'canceled'
- ? { type: 'canceled', reason: error } : { type: 'error', error });
- closeJobAfterDelay(sseJobs, job.id);
- mediaJobEvents.emit(status, job);
- if (status === 'failed') console.error(`❌ media-job [${job.id.slice(0, 8)}] preparation failed: ${error}`);
- else console.log(`🛑 media-job [${job.id.slice(0, 8)}] canceled (was queued)`);
- })());
+ await trackTerminalOperation(persistTerminalTransition(job));
return true;
}
@@ -816,7 +865,8 @@ async function prepareQueuedVideos(jobs = queue.filter((job) => !job.admitting))
if (dispatchQuiesced) break;
if (!error || job.admitting) continue;
await settleQueuedJob(job, { status: 'failed',
- error: `Could not prepare local video model: ${error.message || String(error)}` });
+ error: `Could not prepare local video model: ${error.message || String(error)}` })
+ .catch((failure) => console.error(`❌ media preparation outcome awaiting storage: ${failure.message}`));
}
}
@@ -865,7 +915,7 @@ export function quiesceMediaJobQueue() {
// should cancel them first.
export function removeArchivedJob(jobId) {
const idx = archive.findIndex((j) => j.id === jobId);
- if (idx < 0) return false;
+ if (idx < 0 || archive[idx].durabilityPending) return false;
archive.splice(idx, 1);
// End any SSE clients still attached within the SSE_CLEANUP_DELAY_MS grace
// window before dropping the entry — a bare `sseJobs.delete()` here would
@@ -1099,36 +1149,40 @@ async function runJobLifecycle(job, markDispatched) {
emitter.off?.('activity', onActivity);
emitter.off?.('progress', onActivity);
await drainProgressPersist();
- apply(job);
- job.status = state;
- if (state === 'completed') {
- job.progress = 1;
- job.statusMsg = 'Completed';
- }
- // failed/canceled intentionally retain the last mid-render progress/statusMsg
- // (how far it got) — consumers gate the progress UI on status === 'running',
- // so the residual values are not displayed for terminal jobs.
- job.completedAt = new Date().toISOString();
- if (job.params?.videoProduction) {
- const { settleVideoAttempt } = await import('../creativeDirector/videoExecution.js');
- const tag = job.params.videoProduction;
- await settleVideoAttempt(tag.projectId, tag.attemptId, { jobId: job.id, status: job.params.videoProduction.submissionUncertain || (state === 'failed' && /timeout|timed out|interrupted/i.test(job.error || '')) ? 'uncertain' : state })
- .catch(error => console.error(`❌ Video receipt could not settle: ${error.message}`));
- }
- // Wake the lane finalizer without polling. Some providers emit their
- // terminal event just before their kickoff promise resolves; the promise
- // retains that signal until runJob reaches the await below.
- resolveTerminalState();
- const logPrefix = state === 'completed' ? '✅' : state === 'canceled' ? '🛑' : '❌';
- const logSuffix = state === 'failed' ? `: ${job.error}` : state === 'canceled' ? ' (was running)' : '';
- console.log(`${logPrefix} media-job [${job.id.slice(0, 8)}] ${state}${logSuffix}`);
- const ssePayload =
- state === 'completed' ? { type: 'complete', result: job.result }
- : state === 'canceled' ? { type: 'canceled', reason: job.error }
- : { type: 'error', error: job.error };
- broadcastSse(sseEntry, ssePayload);
- closeJobAfterDelay(sseJobs, job.id);
- mediaJobEvents.emit(state, job);
+ stageTerminalTransition(job, (job) => {
+ apply(job);
+ job.status = state;
+ if (state === 'completed') {
+ job.progress = 1;
+ job.statusMsg = 'Completed';
+ }
+ // failed/canceled intentionally retain the last mid-render progress/statusMsg
+ // (how far it got) — consumers gate the progress UI on status === 'running',
+ // so the residual values are not displayed for terminal jobs.
+ job.completedAt = new Date().toISOString();
+ }, async () => {
+ if (job.params?.videoProduction) {
+ const tag = job.params.videoProduction;
+ const { settleVideoAttempt } = await import('../creativeDirector/videoExecution.js');
+ await settleVideoAttempt(tag.projectId, tag.attemptId, { jobId: job.id, status: job.params.videoProduction.submissionUncertain || (state === 'failed' && /timeout|timed out|interrupted/i.test(job.error || '')) ? 'uncertain' : state })
+ .catch(error => console.error(`❌ Video receipt could not settle: ${error.message}`));
+ }
+ // Wake the lane finalizer without polling. Some providers emit their
+ // terminal event just before their kickoff promise resolves; the promise
+ // retains that signal until runJob reaches the await below.
+ resolveTerminalState();
+ const logPrefix = state === 'completed' ? '✅' : state === 'canceled' ? '🛑' : '❌';
+ const logSuffix = state === 'failed' ? `: ${job.error}` : state === 'canceled' ? ' (was running)' : '';
+ console.log(`${logPrefix} media-job [${job.id.slice(0, 8)}] ${state}${logSuffix}`);
+ const ssePayload =
+ state === 'completed' ? { type: 'complete', result: job.result }
+ : state === 'canceled' ? { type: 'canceled', reason: job.error }
+ : { type: 'error', error: job.error };
+ broadcastSse(sseEntry, ssePayload);
+ closeJobAfterDelay(sseJobs, job.id);
+ mediaJobEvents.emit(state, job);
+ });
+ await persistTerminalTransition(job);
}
const handlers = {
@@ -1523,6 +1577,12 @@ export async function cancelQueuedJobs({ kind } = {}) {
// Cancel: drops a queued job, or sends SIGTERM to a running gen process.
export async function cancelJob(jobId) {
+ const pending = findJob(jobId);
+ if (pending?.durabilityPending) {
+ await persistTerminalTransition(pending);
+ return pending.status === 'canceled' ? { ok: true, status: 'canceled' }
+ : { ok: false, code: 'ALREADY_TERMINAL', status: pending.status, error: 'Job is already finishing' };
+ }
const queueIdx = queue.findIndex((j) => j.id === jobId);
if (queueIdx >= 0) {
const job = queue[queueIdx];
@@ -1553,7 +1613,7 @@ export async function cancelJob(jobId) {
if (isRemoteMediaJob(runningJob)) {
// Durable intent precedes the adapter call so boot recovery resumes
// cancellation rather than silently resurrecting the remote render.
- await persist().catch((e) => console.log(`⚠️ mediaJobQueue persist on remote cancel failed: ${e.message}`));
+ await persist();
}
if (mod?.cancel && mod.cancel(jobId) === false
&& (runningJob.providerInvoked || isRemoteMediaJob(runningJob))) {
@@ -1638,6 +1698,7 @@ export const MEDIA_QUEUE_FLUSH_TIMEOUT_MS = 2000;
// the shutdown budget; never rejects, reporting the outcome instead.
export async function flushMediaJobQueue({ timeoutMs = MEDIA_QUEUE_FLUSH_TIMEOUT_MS } = {}) {
const drain = (async () => {
+ await persist();
while (terminalOperations.size > 0) {
await Promise.allSettled([...terminalOperations]);
}
@@ -1666,6 +1727,7 @@ export function __resetForTests() {
cloudRunning.length = 0;
remoteRunning.length = 0;
archive.length = 0;
+ pendingTransitions.clear();
videoHolds.clear();
sseJobs.clear();
workerStarted = false;
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index ed6b2bd476..7375423a8e 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -1988,7 +1988,9 @@ describe('mediaJobQueue unreadable snapshot (#4115)', () => {
// …and so is every write the running queue would normally make.
stubs.generateVideo.mockImplementation(() => new Promise(() => {}));
- await mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'after a bad boot' } });
+ await expect(mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'after a bad boot' } }))
+ .rejects.toMatchObject({ status: 503, code: mediaJobQueue.MEDIA_QUEUE_PERSIST_FAILED });
+ expect(stubs.generateVideo).not.toHaveBeenCalled();
await flush();
expect(
readFileSync(file, 'utf8'),
@@ -2364,7 +2366,7 @@ describe('local video failure holds', () => {
expect(mediaJobQueue.getJob(next).status).toBe('running');
});
- it('recovers independent work while damaged holds protect saved and new local video until explicit resume', async () => {
+ it('withholds dispatch and new admissions when damaged holds block durable snapshots', async () => {
const file = join(tempDataDir, 'media-jobs.json');
const savedVideos = ['retained-mlx', 'retained-cuda'];
const snapshot = JSON.stringify({ jobs: [
@@ -2387,30 +2389,14 @@ describe('local video failure holds', () => {
await tick();
expect(stubs.generateVideo).not.toHaveBeenCalled();
expect(mediaJobQueue.getJob('interrupted-video').status).toBe('failed');
- expect(mediaJobQueue.getJob('saved-remote')).toMatchObject({ status: 'running', params: { remoteMedia: { reconcile: true } } });
- expect(mediaJobQueue.getJob('saved-cloud').status).toBe('running');
- expect(mediaJobQueue.getJob('saved-training')).toMatchObject({ status: 'running', params: { reattach: true } });
- (await import('../loraTraining/events.js')).trainingEvents.emit('completed', { generationId: 'saved-training' });
- await tick();
- expect(mediaJobQueue.getJob('saved-image').status).toBe('running');
- imageGenEvents.emit('completed', { generationId: 'saved-image' });
- await flush();
- const newlyQueued = await submit('example-other');
- await tick();
- const retainedIds = [...savedVideos, newlyQueued];
- for (const id of retainedIds) expect(mediaJobQueue.getJob(id)).toMatchObject({ status: 'queued', hold: { scope: 'local-video', heldJobCount: 3 } });
- expect(mediaJobQueue.isVideoModelHeld('example-cuda', 'cuda_video')).toBe(true);
- expect(mediaJobQueue.isVideoModelHeld('example-other', 'mlx_video')).toBe(true);
- expect(stubs.generateVideo).not.toHaveBeenCalled();
+ for (const generate of [stubs.generateImage, stubs.generateImageCodex, stubs.generateAudioRemote, stubs.runTraining]) {
+ expect(generate).not.toHaveBeenCalled();
+ }
+ await expect(submit('example-other')).rejects.toMatchObject({ code: mediaJobQueue.MEDIA_QUEUE_PERSIST_FAILED });
expect(readFileSync(file, 'utf8')).toBe(snapshot);
const [recoveryHold] = mediaJobQueue.listVideoHolds();
- expect(recoveryHold).toMatchObject({ scope: 'local-video', heldJobCount: 3 });
- const { sanitizeJob } = await import('./sanitizeJob.js');
- expect(sanitizeJob(mediaJobQueue.getJob(savedVideos[0])).hold).toEqual(recoveryHold);
- expect(await mediaJobQueue.resumeVideoHold(recoveryHold.id)).toBe(true);
- expect(mediaJobQueue.listVideoHolds()).toEqual([]);
- for (const id of retainedIds) { await tick(); await finish(id, null); }
- expect(stubs.generateVideo.mock.calls.map(([params]) => params.jobId)).toEqual(retainedIds);
+ expect(recoveryHold).toMatchObject({ scope: 'local-video' });
+ await expect(mediaJobQueue.resumeVideoHold(recoveryHold.id)).rejects.toThrow('storage is blocked');
expect(readFileSync(file, 'utf8')).toBe(snapshot);
});
});
@@ -2476,6 +2462,7 @@ describe('local video preparation failures', () => {
mediaJobQueue.attachSseClient(omitted.jobId, res);
expect(res.write.mock.calls.flat().join('')).toContain('Could not prepare local video model');
videoGenEvents.emit('completed', { generationId: explicit.jobId });
+ await flush(); // Durable terminal settlement releases the lane before the worker tick.
await tick();
expect(mediaJobQueue.getJob(waiting.jobId).status).toBe('running');
videoGenEvents.emit('completed', { generationId: waiting.jobId });
@@ -2867,3 +2854,108 @@ describe('pending-job ceiling', () => {
await expect(mediaJobQueue.enqueueJob({ kind: 'video', params: { prompt: 'full again' } })).rejects.toMatchObject(queueFull);
});
});
+
+// #9737: a terminal UI outcome must describe a durable row, and provider
+// execution must never outrun the running snapshot that prevents local replay.
+describe('durable execution and terminal settlement', () => {
+ let storageWrite;
+ beforeEach(async () => {
+ storageWrite = atomicWriteSpy.getMockImplementation();
+ vi.useFakeTimers();
+ stubs.generateVideo.mockImplementation(async () => ({}));
+ await mediaJobQueue.initMediaJobQueue();
+ });
+ afterEach(() => { atomicWriteSpy.mockImplementation(storageWrite); vi.clearAllTimers(); vi.useRealTimers(); });
+
+ it('withholds generator execution until the running snapshot succeeds', async () => {
+ const { jobId } = await mediaJobQueue.enqueueJob({ kind: 'video', params: { modelId: 'example-cuda' } });
+ const release = holdNextWrite();
+ await vi.advanceTimersByTimeAsync(200);
+ expect(stubs.generateVideo).not.toHaveBeenCalled();
+ expect(persistedJobs().find((j) => j.id === jobId).status).toBe('queued');
+ release();
+ await flush();
+ expect(stubs.generateVideo).toHaveBeenCalledTimes(1);
+ expect(persistedJobs().find((j) => j.id === jobId).status).toBe('running');
+ videoGenEvents.emit('completed', { generationId: jobId });
+ await flush();
+ });
+
+ it('never dispatches after a failed running write and recovers only its storage settlement', async () => {
+ const { jobId } = await mediaJobQueue.enqueueJob({ kind: 'video', params: { modelId: 'example-cuda' } });
+ const realWrite = atomicWriteSpy.getMockImplementation();
+ atomicWriteSpy.mockRejectedValue(new Error('disk full'));
+ await vi.advanceTimersByTimeAsync(200);
+ await flush();
+ expect(stubs.generateVideo).not.toHaveBeenCalled();
+ expect(mediaJobQueue.getJob(jobId).status).toBe('running');
+ expect(persistedJobs().find((j) => j.id === jobId).status).toBe('queued');
+ atomicWriteSpy.mockImplementation(realWrite);
+ await expect(mediaJobQueue.flushMediaJobQueue()).resolves.toEqual({ ok: true });
+ expect(mediaJobQueue.getJob(jobId).status).toBe('failed');
+ expect(persistedJobs().find((j) => j.id === jobId).status).toBe('failed');
+ expect(stubs.generateVideo).not.toHaveBeenCalled();
+ });
+
+ it('rejects an undurable queued cancellation, retains uploads, and acknowledges once on recovery', async () => {
+ mediaJobQueue.quiesceMediaJobQueue();
+ const upload = join(tempDataDir, 'uploads', 'example.png');
+ mkdirSync(join(tempDataDir, 'uploads'), { recursive: true });
+ writeFileSync(upload, 'synthetic image');
+ const { jobId } = await mediaJobQueue.enqueueJob({ kind: 'video', params: { modelId: 'example-cuda', uploadedTempPath: upload } });
+ const canceled = vi.fn();
+ mediaJobQueue.mediaJobEvents.on('canceled', canceled);
+ const realWrite = atomicWriteSpy.getMockImplementation();
+ atomicWriteSpy.mockRejectedValue(new Error('disk full'));
+ await expect(mediaJobQueue.cancelJob(jobId)).rejects.toMatchObject({ status: 503, code: mediaJobQueue.MEDIA_QUEUE_PERSIST_FAILED });
+ expect(canceled).not.toHaveBeenCalled();
+ expect(mediaJobQueue.getJob(jobId).status).toBe('queued');
+ expect(persistedJobs().find((j) => j.id === jobId).status).toBe('queued');
+ expect(existsSync(upload)).toBe(true);
+ const { sanitizeJob } = await import('./sanitizeJob.js');
+ expect(mediaJobQueue.listQueueJobs().map(sanitizeJob)).toEqual([expect.objectContaining({
+ id: jobId, status: 'queued', statusMsg: 'Outcome pending: media queue storage unavailable',
+ })]);
+ expect(mediaJobQueue.removeArchivedJob(jobId)).toBe(false);
+ atomicWriteSpy.mockImplementation(realWrite);
+ await expect(mediaJobQueue.cancelJob(jobId)).resolves.toEqual({ ok: true, status: 'canceled' });
+ await flush();
+ expect(canceled).toHaveBeenCalledTimes(1);
+ expect(existsSync(upload)).toBe(false);
+ vi.clearAllTimers();
+ mediaJobQueue.__resetForTests();
+ await importFresh();
+ await mediaJobQueue.initMediaJobQueue();
+ await vi.advanceTimersByTimeAsync(200);
+ expect(mediaJobQueue.getJob(jobId).status).toBe('canceled');
+ expect(stubs.generateVideo).not.toHaveBeenCalled();
+ });
+
+ it('withholds completion and its result until storage recovers without generating again', async () => {
+ const { jobId } = await mediaJobQueue.enqueueJob({ kind: 'video', params: { modelId: 'example-cuda' } });
+ await vi.advanceTimersByTimeAsync(200);
+ await flush();
+ const completed = vi.fn();
+ mediaJobQueue.mediaJobEvents.on('completed', completed);
+ const realWrite = atomicWriteSpy.getMockImplementation();
+ atomicWriteSpy.mockRejectedValue(new Error('disk full'));
+ videoGenEvents.emit('completed', { generationId: jobId, output: 'example.mp4' });
+ await flush();
+ expect(completed).not.toHaveBeenCalled();
+ expect(mediaJobQueue.getJob(jobId)).toMatchObject({ status: 'running' });
+ expect(mediaJobQueue.getJob(jobId).result).toBeUndefined();
+ expect(persistedJobs().find((j) => j.id === jobId).status).toBe('running');
+ atomicWriteSpy.mockImplementation(realWrite);
+ await expect(mediaJobQueue.flushMediaJobQueue()).resolves.toEqual({ ok: true });
+ expect(completed).toHaveBeenCalledTimes(1);
+ expect(stubs.generateVideo).toHaveBeenCalledTimes(1);
+ expect(mediaJobQueue.getJob(jobId)).toMatchObject({ status: 'completed', result: { output: 'example.mp4' } });
+ vi.clearAllTimers();
+ mediaJobQueue.__resetForTests();
+ await importFresh();
+ await mediaJobQueue.initMediaJobQueue();
+ await vi.advanceTimersByTimeAsync(200);
+ expect(mediaJobQueue.getJob(jobId).status).toBe('completed');
+ expect(stubs.generateVideo).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/server/services/mediaJobQueue/sanitizeJob.js b/server/services/mediaJobQueue/sanitizeJob.js
index 1c555dce10..9c6d289cd3 100644
--- a/server/services/mediaJobQueue/sanitizeJob.js
+++ b/server/services/mediaJobQueue/sanitizeJob.js
@@ -52,6 +52,10 @@ const executionProvenance = (value) => {
export function sanitizeJob(job) {
if (!job) return job;
+ if (job.durabilityPending) {
+ job = { ...job,
+ statusMsg: job.persistenceError ? 'Outcome pending: media queue storage unavailable' : 'Saving outcome' };
+ }
const safeParams = job.params
? Object.fromEntries(Object.entries(job.params)
.filter(([key]) => PARAM_ALLOWLIST.has(key) || key === 'musicStudio')
diff --git a/server/services/mediaJobQueue/videoHolds.js b/server/services/mediaJobQueue/videoHolds.js
index cd2153d2b3..0bbe9aeaec 100644
--- a/server/services/mediaJobQueue/videoHolds.js
+++ b/server/services/mediaJobQueue/videoHolds.js
@@ -35,12 +35,12 @@ export function createVideoHolds() {
}
if (!readable) {
// Unknown hold metadata cannot identify a safe local video cohort.
- // Cover all local video, including new submissions, while other kinds
- // recover normally. The queue latches persistence off to preserve the
+ // Cover all local video. The queue also disables dispatch and admission
+ // because its writer is latched off to preserve the
// original file; this recovery hold exists only in this process.
recoveryHold = { id: randomUUID(), scope: 'local-video', modelId: '*', runtime: '*',
classification: 'invalid-hold-metadata', heldAt: new Date().toISOString(),
- cause: 'Saved video holds are damaged. Repair the queue snapshot and restart to restore persistence. Resume releases all local video holds for this session.' };
+ cause: 'Saved video holds are damaged. Repair the queue snapshot and restart to restore persistence and dispatch.' };
}
return readable;
},