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: retain classified video failures across dispatch and chains (#6282)

[._.]/ Adam Eivybc4064b51937
diff --git a/server/lib/videoFailure.js b/server/lib/videoFailure.js
index 2da1c69983..684c8c5e7d 100644
--- a/server/lib/videoFailure.js
+++ b/server/lib/videoFailure.js
@@ -1,48 +1,58 @@
/** Bounded, local-only video failure summaries shared by the runner and queue. */
+import { createHash } from 'crypto';
import { scrubSecretTokens } from './secretText.js';
const MAX_TAIL_BYTES = 8192;
const MAX_CAUSE_LENGTH = 240;
+const failureRecord = (classification, cause, identity = cause) => ({
+ classification,
+ cause,
+ // Streak-only evidence. Never projected or persisted in an active hold. Keep
+ // diagnostic identifiers distinct even when the display redacts quotes.
+ signature: createHash('sha256').update(`${classification}\n${identity.toLowerCase()}`).digest('hex'),
+});
-// Only diagnostic-shaped lines qualify. Progress, prompts, JSON and bare exit
-// codes cannot establish a repeated engine failure.
-export function normalizeVideoFailure(error, { prompts = [] } = {}) {
- if (typeof error !== 'string') return null;
- let text = error.slice(-MAX_TAIL_BYTES).replace(/\x1b\[[0-9;]*m/g, '');
- for (const prompt of prompts.filter((p) => typeof p === 'string' && p)) {
- text = text.replaceAll(prompt, '[prompt]');
- }
+const scrubCause = (text) => scrubSecretTokens(text)
+ .replace(/\b(?:https?|file):\/\/\S+/gi, '[url]')
+ .replace(/\b(?:api[_-]?key|token|password|secret|authorization)\s*[:=]\s*\S+/gi, '[credential]')
+ // An unquoted path has no reliable ending delimiter (spaces are legal on
+ // both platforms). Redact the remainder rather than leaking path fragments.
+ .replace(/(?:[A-Za-z]:[\\/]|\\\\|\/(?=\S))[^\r\n]*/g, '[path]')
+ .replace(/\bprompt\b.*$/i, '[prompt]')
+ .replace(/\b0x[\da-f]+\b/gi, '[address]')
+ .replace(/\s+/g, ' ').trim();
+
+// Only diagnostic-shaped lines or a producer's explicit error code qualify.
+// Progress, prompts, signal advice and bare exit codes are not cause evidence.
+export function normalizeVideoFailure(error, { prompts = [], code = error?.code } = {}) {
+ let text = typeof error === 'string' ? error : error?.message;
+ if (typeof text !== 'string') return null;
+ for (const prompt of prompts.filter((p) => typeof p === 'string' && p)) text = text.replaceAll(prompt, '[prompt]');
+ text = text.slice(-MAX_TAIL_BYTES).replace(/\x1b\[[0-9;]*m/g, '');
+ if (/^(?:Generation failed:\s*)?Exit code \d+\s*$/i.test(text.trim())) return null;
const missing = text.match(/(?:No module named|Python module) ['"]([\w.]+)['"]/);
- if (missing) return { classification: 'missing-module', cause: `Python module ${missing[1].slice(0, 128)} is missing` };
- if (/\b(?:CUDA|Metal|MPS|GPU).*out of memory|out of memory.*\b(?:CUDA|Metal|MPS|GPU)/i.test(text)) {
- return { classification: 'out-of-memory', cause: 'GPU memory exhausted' };
+ if (missing && scrubSecretTokens(missing[1]) === missing[1]) {
+ return failureRecord('missing-module', `Python module ${missing[1].slice(0, 128)} is missing`);
}
- if (/Metal command-buffer watchdog|kIOGPUCommandBufferCallbackErrorImpactingInteractivity/.test(text)) {
- return { classification: 'metal-watchdog', cause: 'Metal command-buffer watchdog stopped the render' };
+ if (/\b(?:CUDA|Metal|MPS|GPU).*out of memory|out of memory.*\b(?:CUDA|Metal|MPS|GPU)|GPU memory exhausted/i.test(text)) {
+ return failureRecord('out-of-memory', 'GPU memory exhausted');
}
if (/watchdog timeout: no runner output/.test(text)) {
- return { classification: 'idle-timeout', cause: 'Video runtime stopped reporting progress' };
+ return failureRecord('idle-timeout', 'Video runtime stopped reporting progress');
}
if (/\b(?:ENOENT|EACCES)\b/.test(text) && /spawn/i.test(text)) {
- const code = text.match(/\b(ENOENT|EACCES)\b/)[1];
- return { classification: 'runtime-launch', cause: `Video runtime could not start (${code})` };
+ return failureRecord('runtime-launch', `Video runtime could not start (${text.match(/\b(ENOENT|EACCES)\b/)[1]})`);
}
if (/python.*not configured/i.test(text)) {
- return { classification: 'runtime-configuration', cause: 'Python runtime is not configured' };
+ return failureRecord('runtime-configuration', 'Python runtime is not configured');
}
const exception = text.match(/(?:^|\n|Exit code \d+:\s*|runJob threw:\s*)([\w.]*?(?:Error|Exception)):\s*([^\r\n]+)/);
- if (!exception) return null;
- const cause = scrubSecretTokens(exception[2])
- // Drop URL, credential assignments, quoted payloads and machine paths.
- .replace(/\b(?:https?|file):\/\/\S+/gi, '[url]')
- .replace(/\b(?:api[_-]?key|token|password|secret|authorization)\s*[:=]\s*\S+/gi, '[credential]')
- .replace(/(['"])(?:\\.|(?!\1).)*?\1/g, '[value]')
- .replace(/(?:[A-Za-z]:[\\/]|\\\\|\/(?!\s))[^\s,;)]*/g, '[path]')
- .replace(/\bprompt\b.*$/i, '[prompt]')
- .replace(/\b0x[\da-f]+\b/gi, '[address]')
- .replace(/\s+/g, ' ').trim().slice(0, MAX_CAUSE_LENGTH);
+ const classification = exception?.[1] || (/^[A-Z][A-Z0-9_]{0,127}$/.test(code || '') ? code : null);
+ if (!classification || scrubSecretTokens(classification) !== classification) return null;
+ const identity = scrubCause(exception?.[2] || text);
+ const cause = identity.replace(/(['"])(?:\\.|(?!\1).)*?\1/g, '[value]').slice(0, MAX_CAUSE_LENGTH);
if (!/[a-z]{3}/i.test(cause.replace(/\[[^\]]*\]/g, ''))) return null;
- return { classification: exception[1].toLowerCase().slice(0, 128), cause };
+ return failureRecord(classification.toLowerCase().slice(0, 128), cause, identity);
}
export function createVideoDiagnosticTail() {
@@ -52,14 +62,20 @@ export function createVideoDiagnosticTail() {
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
tails[stream] = Buffer.concat([tails[stream], bytes.subarray(-MAX_TAIL_BYTES)]).subarray(-MAX_TAIL_BYTES);
},
- summary(options) {
- // Prefer the final stderr exception; some runtimes only use stdout.
+ failure(options) {
+ // Prefer stderr; some runtimes only write exceptions to stdout. Signal
+ // classification comes from actual child evidence, never fallback advice.
for (const stream of ['stderr', 'stdout']) {
const lines = tails[stream].toString('utf8').split(/[\r\n]+/).slice(-40).reverse();
- for (const line of lines) {
- if (!/^(?:[\w.]*?(?:Error|Exception)):\s/.test(line.trim())) continue;
- const failure = normalizeVideoFailure(line.trim(), options);
- if (failure) return `${line.trim().split(':')[0]}: ${failure.cause}`;
+ for (const raw of lines) {
+ let line = raw.replace(/\x1b\[[0-9;]*m/g, '').trim();
+ for (const prompt of (options?.prompts || []).filter((p) => typeof p === 'string' && p)) line = line.replaceAll(prompt, '[prompt]');
+ if (/^(?:prompt|STATUS|STAGE|DOWNLOAD|RUNTIME):/i.test(line) || line.startsWith('{')) continue;
+ const metal = line.match(/kIOGPUCommandBufferCallbackError(OutOfMemory|InnocentVictim|Timeout|ImpactingInteractivity)\b/);
+ if (stream === 'stderr' && metal) return failureRecord('metal-command-buffer', `Metal command buffer failed: ${metal[1]}`);
+ if (!/^(?:[\w.]*?(?:Error|Exception)):\s/.test(line)) continue;
+ const failure = normalizeVideoFailure(line, options);
+ if (failure) return { ...failure, summary: `${line.split(':')[0].slice(0, 128)}: ${failure.cause}` };
}
}
return null;
diff --git a/server/lib/videoFailure.test.js b/server/lib/videoFailure.test.js
index 7ee98f0b48..88a53477d7 100644
--- a/server/lib/videoFailure.test.js
+++ b/server/lib/videoFailure.test.js
@@ -8,9 +8,9 @@ describe('local video diagnostic privacy boundary', () => {
tail.push('stderr', 'RuntimeError: obsolete exception\n');
tail.push('stderr', 'x'.repeat(20000));
tail.push('stdout', 'STAGE:load-model\nSTATUS:working\nprompt: RuntimeError: invented prose\n');
- expect(tail.summary()).toBeNull();
+ expect(tail.failure()?.summary || null).toBeNull();
tail.push('stderr', '\nRuntimeError: shader compilation failed');
- expect(tail.summary()).toBe('RuntimeError: shader compilation failed');
+ expect(tail.failure()?.summary || null).toBe('RuntimeError: shader compilation failed');
});
it('scrubs conditioning, tokens, credentials and POSIX/Windows paths before identity or display', () => {
@@ -22,6 +22,18 @@ describe('local video diagnostic privacy boundary', () => {
expect(failure.cause.length).toBeLessThanOrEqual(240);
expect(normalizeVideoFailure('RuntimeError: shape mismatch')).not.toEqual(normalizeVideoFailure('RuntimeError: shader compilation failed'));
expect(normalizeVideoFailure("ModuleNotFoundError: No module named 'example_runtime'"))
- .toEqual({ classification: 'missing-module', cause: 'Python module example_runtime is missing' });
+ .toMatchObject({ classification: 'missing-module', cause: 'Python module example_runtime is missing' });
});
});
+
+it('keeps redacted identifiers distinct and removes entire paths containing spaces', () => {
+ const first = normalizeVideoFailure("AttributeError: 'Tokenizer' object has no attribute 'encode'");
+ const second = normalizeVideoFailure("AttributeError: 'Pipeline' object has no attribute 'decode'");
+ expect(first.cause).toBe(second.cause);
+ expect(first.signature).not.toBe(second.signature);
+ for (const path of ['/mock/private folder/encoder file', 'C:\\mock\\private folder\\encoder file']) {
+ const failure = normalizeVideoFailure(`RuntimeError: Substituted text encoder is missing: ${path}`);
+ expect(failure.cause).toBe('Substituted text encoder is missing: [path]');
+ expect(failure.signature).toMatch(/^[a-f0-9]{64}$/);
+ }
+});
diff --git a/server/services/federatedMediaProvider.js b/server/services/federatedMediaProvider.js
index da45f4366a..c45ad0faa4 100644
--- a/server/services/federatedMediaProvider.js
+++ b/server/services/federatedMediaProvider.js
@@ -557,7 +557,8 @@ const federatedLaneConcurrency = (kinds) => (kinds.length === 0 ? 1 : Math.min(
*/
function activeQueueSnapshot(config, kinds) {
const active = listJobs().filter((job) =>
- ACTIVE_STATUSES.has(job.status) && !isRemoteMediaJob(job),
+ ACTIVE_STATUSES.has(job.status) && !isRemoteMediaJob(job)
+ && !(job.status === 'queued' && job.hold),
);
let providerActive = 0;
let queued = 0;
diff --git a/server/services/federatedMediaProvider.test.js b/server/services/federatedMediaProvider.test.js
index bc16cf2bb3..73876f2db2 100644
--- a/server/services/federatedMediaProvider.test.js
+++ b/server/services/federatedMediaProvider.test.js
@@ -317,6 +317,16 @@ describe('federated media provider capacity and idempotency', () => {
expect(status.queue).toMatchObject({ totalActive: 2, providerActive: 1, running: 1, queued: 0 });
});
+ it('admits unrelated peer audio while retained local videos reach the queue cap', async () => {
+ state.jobs = [1, 2, 3].map((id) => ({ id: `held-${id}`, kind: 'video', status: 'queued',
+ hold: { cause: 'local diagnostic' }, owner: null }));
+ const status = await getFederatedMediaProviderStatus(config());
+ expect(status.queue).toMatchObject({ accepting: true, totalActive: 0 });
+ expect(JSON.stringify(status)).not.toContain('local diagnostic');
+ const result = await submitFederatedMediaJob({ callerId: 'peer-example', config: config(), input: input(), idempotencyKey: 'while-held' });
+ expect(result.job).toMatchObject({ status: 'queued', kind: 'audio' });
+ });
+
it('queues allowlisted audio without exposing the prompt in its response', async () => {
const result = await submitFederatedMediaJob({
callerId: 'peer-example', config: config(), input: input(), idempotencyKey: 'commission-1',
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index 922244f004..aa365c5dab 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -647,12 +647,13 @@ function startLaneJob(job, { lane }) {
// not configured). Recover so a single bad job can't freeze its lane.
console.log(`❌ media-job [${job.id.slice(0, 8)}] ${label} runJob threw: ${err.message}`);
if (job.status === 'running') {
- job.status = 'failed';
+ job.status = job.cancelRequested ? 'canceled' : 'failed';
+ videoHolds.captureFailure(job, err);
job.error = `runJob threw: ${err.message}`;
job.completedAt = new Date().toISOString();
broadcastSse(ensureSseEntry(job.id), { type: 'error', error: job.error });
closeJobAfterDelay(sseJobs, job.id);
- mediaJobEvents.emit('failed', job);
+ mediaJobEvents.emit(job.status, job);
}
}
// Count once, after every terminal path (including pre-dispatch throws),
@@ -862,7 +863,7 @@ function makeGenDispatcher(emitter, job, handlers) {
}
};
const onCompleted = (e) => { if (e.generationId === job.id) handlers.completed(e); };
- const onFailed = (e) => { if (e.generationId === job.id) handlers.failed({ error: e.error }); };
+ const onFailed = (e) => { if (e.generationId === job.id) handlers.failed(e); };
return {
attach() {
emitter.on('progress', onProgress);
@@ -1007,7 +1008,10 @@ async function runJob(job) {
return;
}
trackTerminalOperation(
- terminate('failed', (j) => { j.error = payload.error || 'unknown error'; })
+ terminate('failed', (j) => {
+ j.error = payload.error || 'unknown error';
+ videoHolds.captureFailure(j, j.error, payload);
+ })
.catch((e) => console.log(`⚠️ media-job [${job.id.slice(0, 8)}] terminal handler failed: ${e.message}`)),
);
},
@@ -1155,7 +1159,7 @@ async function runJob(job) {
for (const p of normalizeTempPaths(job.params?.uploadedTempPaths)) {
await safeUnlinkUpload(p);
}
- handlers.failed({ error: err.message });
+ handlers.failed({ error: err.message, code: err.code });
}
// The gen modules emit completed/failed asynchronously after kickoff. Await
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index 2753b05702..52f4d9309b 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -1722,6 +1722,7 @@ describe('local video failure holds', () => {
expect(existsSync(upload)).toBe(true);
const persisted = JSON.parse(readFileSync(join(tempDataDir, 'media-jobs.json'), 'utf8'));
expect(persisted.videoHolds).toHaveLength(1);
+ expect(persisted.videoHolds[0]).not.toHaveProperty('signature');
vi.clearAllTimers();
mediaJobQueue.__resetForTests();
@@ -1762,7 +1763,9 @@ describe('local video failure holds', () => {
});
it('resets on success or a different cause, ignores cancellation, and excludes bare exit codes', async () => {
- const errors = ['RuntimeError: shape mismatch', 'RuntimeError: shape mismatch', null,
+ const errors = ["AttributeError: 'Tokenizer' object has no attribute 'encode'",
+ "AttributeError: 'Pipeline' object has no attribute 'decode'",
+ "AttributeError: 'Tokenizer' object has no attribute 'encode'", 'RuntimeError: shape mismatch', 'RuntimeError: shape mismatch', null,
'RuntimeError: shader failed', 'RuntimeError: shader failed', 'Exit code 1',
'RuntimeError: shape mismatch', 'RuntimeError: shader failed', 'RuntimeError: shader failed'];
for (const error of errors) {
@@ -1778,7 +1781,7 @@ describe('local video failure holds', () => {
});
it('counts pre-dispatch rejection once and resumes with a cleared streak', async () => {
- stubs.generateVideo.mockRejectedValue(new Error('Python is not configured'));
+ stubs.generateVideo.mockRejectedValue(Object.assign(new Error("Example runtime is not installed. Install or repair it from Video Gen's model setup panel."), { code: 'EXAMPLE_VENV_MISSING' }));
const ids = Array.from({ length: 4 }, () => submit());
for (let i = 0; i < 4; i += 1) await tick();
expect(stubs.generateVideo).toHaveBeenCalledTimes(3);
@@ -1791,6 +1794,21 @@ describe('local video failure holds', () => {
expect(mediaJobQueue.getJob(next).status).toBe('failed');
});
+ it('uses structured signal evidence and ignores advisory text when no cause was found', async () => {
+ const { createVideoDiagnosticTail } = await import('../../lib/videoFailure.js');
+ const ids = Array.from({ length: 6 }, () => submit());
+ const causes = ['OutOfMemory', 'InnocentVictim', null, 'Timeout', 'Timeout'];
+ for (const [i, cause] of causes.entries()) {
+ await tick();
+ const tail = createVideoDiagnosticTail();
+ if (cause) tail.push('stderr', `kIOGPUCommandBufferCallbackError${cause}`);
+ videoGenEvents.emit('failed', { generationId: ids[i], error: 'Render aborted: Metal command-buffer watchdog advice', failure: tail.failure() });
+ await flush();
+ }
+ await tick();
+ expect(mediaJobQueue.getJob(ids[5]).status).toBe('running');
+ });
+
it('loads legacy jobs without treating startup reconciliation as an engine failure', async () => {
writeFileSync(join(tempDataDir, 'media-jobs.json'), JSON.stringify({ jobs: [
...[1, 2, 3].map((n) => ({ id: `interrupted-${n}`, kind: 'video', status: 'running', params: { modelId: 'example-mlx' } })),
diff --git a/server/services/mediaJobQueue/videoHolds.js b/server/services/mediaJobQueue/videoHolds.js
index 2b3d42eb7d..1b22b6dd21 100644
--- a/server/services/mediaJobQueue/videoHolds.js
+++ b/server/services/mediaJobQueue/videoHolds.js
@@ -51,21 +51,24 @@ export function createVideoHolds() {
? { ...holds.get(key), heldJobCount: counts.get(key) } : undefined;
}
},
+ captureFailure(job, error, { code, failure } = {}) {
+ job.videoFailure = failure !== undefined ? failure : normalizeVideoFailure(error, {
+ code, prompts: [job.params?.prompt, job.params?.negativePrompt, ...(job.params?.chunkPrompts || [])],
+ });
+ },
recordTerminal(job) {
if (!isLocalVideo(job) || !job.videoCohort || job.status === 'canceled') return;
const key = cohortKey(job.videoCohort);
if (job.status === 'completed') { streaks.delete(key); return; }
if (job.status !== 'failed') return;
- const failure = normalizeVideoFailure(job.error, {
- prompts: [job.params?.prompt, job.params?.negativePrompt, ...(job.params?.chunkPrompts || [])],
- });
+ const failure = job.videoFailure;
if (!failure) { streaks.delete(key); return; }
- const signature = JSON.stringify([failure.classification, failure.cause.toLowerCase()]);
+ const signature = failure.signature;
const previous = streaks.get(key);
const count = previous?.signature === signature ? previous.count + 1 : 1;
streaks.set(key, { signature, count });
if (count >= 3 && !holds.has(key)) {
- holds.set(key, { id: randomUUID(), ...job.videoCohort, ...failure, heldAt: new Date().toISOString() });
+ holds.set(key, { id: randomUUID(), ...job.videoCohort, classification: failure.classification, cause: failure.cause, heldAt: new Date().toISOString() });
}
},
resume(id) {
diff --git a/server/services/videoGen/chainedVideo.js b/server/services/videoGen/chainedVideo.js
index 1cf35320d2..7291b5347b 100644
--- a/server/services/videoGen/chainedVideo.js
+++ b/server/services/videoGen/chainedVideo.js
@@ -1,3 +1,4 @@
+import { normalizeVideoFailure } from '../../lib/videoFailure.js';
/** Multi-chunk local-video orchestration. */
import { join } from 'path';
@@ -225,7 +226,7 @@ export async function generateChainedVideo({ chunks, chunkPrompts, contextFrames
const onFailed = (e) => {
if (e.generationId !== innerJobId) return;
detach();
- reject(new Error(e.error || 'chunk failed'));
+ resolve({ error: e.error || 'chunk failed', failure: e.failure });
};
videoGenEvents.on('progress', onProgress);
videoGenEvents.on('completed', onCompleted);
@@ -309,10 +310,11 @@ export async function generateChainedVideo({ chunks, chunkPrompts, contextFrames
broadcastSse(outerJob, { type: 'complete', result: payload });
closeJobAfterDelay(videoJobState.jobs, outerJobId);
};
- const finishFail = (error) => {
+ const failureOptions = { prompts: [rest.prompt, rest.negativePrompt, ...(chunkPrompts || [])] };
+ const finishFail = (error, failure = normalizeVideoFailure(error, failureOptions)) => {
if (videoJobState.activeChain === chainState) videoJobState.activeChain = null;
cleanupContextClips();
- videoGenEvents.emit('failed', { generationId: outerJobId, error });
+ videoGenEvents.emit('failed', { generationId: outerJobId, error, failure });
broadcastSse(outerJob, { type: 'error', error });
closeJobAfterDelay(videoJobState.jobs, outerJobId);
};
@@ -327,10 +329,10 @@ export async function generateChainedVideo({ chunks, chunkPrompts, contextFrames
return;
}
// eslint-disable-next-line no-await-in-loop
- const completed = await runChunk(i).catch((err) => ({ error: err.message }));
+ const completed = await runChunk(i).catch((err) => ({ error: err.message, failure: normalizeVideoFailure(err, failureOptions) }));
if (completed?.error) {
await setHistoryItemsHidden(chunkIds, true);
- finishFail(completed.error);
+ finishFail(completed.error, completed.failure);
return;
}
// The chunk's output file is always <innerJobId>.mp4 under PATHS.videos
@@ -440,7 +442,7 @@ export async function generateChainedVideo({ chunks, chunkPrompts, contextFrames
});
})().catch((err) => {
console.log(`❌ chain orchestration crashed [${outerJobId.slice(0, 8)}]: ${err.message}`);
- finishFail(err.message);
+ finishFail(err.message, normalizeVideoFailure(err, failureOptions));
});
// Match the synchronous shape of generateVideo so the route's response
diff --git a/server/services/videoGen/generateVideo.js b/server/services/videoGen/generateVideo.js
index 43d8d1ff29..4e561be921 100644
--- a/server/services/videoGen/generateVideo.js
+++ b/server/services/videoGen/generateVideo.js
@@ -1,3 +1,4 @@
+import { normalizeVideoFailure } from '../../lib/videoFailure.js';
/**
* Video Gen — local render runner (mlx_video on macOS, diffusers on Windows).
*
@@ -897,7 +898,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
const reason = err.message || 'Failed to build video gen args';
console.log(`❌ Video generation buildArgs error [${jobId.slice(0, 8)}]: ${reason}`);
broadcastSse(job, { type: 'error', error: reason });
- videoGenEvents.emit('failed', { generationId: jobId, error: reason });
+ videoGenEvents.emit('failed', { generationId: jobId, error: reason, failure: normalizeVideoFailure(err, { prompts: [prompt, negativePrompt] }) });
void cleanupTempFiles({ includeUploads: true, includeUntrackedAudio: true });
void rmGuarded(stepwiseDir, { recursive: true, force: true });
closeJobAfterDelay(videoJobState.jobs, jobId);
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index 0a8c059fed..43b488ec56 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -3368,6 +3368,24 @@ describe('generateVideo — BYOV missing-python-module failure path (#1833 regre
// re-exported (`export * from './runtimes.js'`) but NOT bound in local.js's
// own scope — which would make the reference here throw a ReferenceError, so
// the terminal 'failed' event never carries the venv-specific reason.
+ it('classifies the first emitted missing-venv failure before the render rejects', async () => {
+ vi.resetModules();
+ const { generateVideo: gv } = await import('./local.js');
+ const { videoGenEvents: events } = await import('./events.js');
+ const { BYOV_RUNTIME_INFO } = await import('./runtimes.js');
+ const { existsSync } = await import('fs');
+ const originalExists = vi.mocked(existsSync).getMockImplementation();
+ vi.mocked(existsSync).mockImplementation((path) => path !== BYOV_RUNTIME_INFO.ltx2.venvPython);
+ const failed = new Promise((resolve) => events.once('failed', resolve));
+ try {
+ await expect(gv({ jobId: 'example-missing-venv', modelId: 'ltx2_unified', prompt: 'invented clip',
+ width: 512, height: 512, numFrames: 25, fps: 24, mode: 'text' })).rejects.toMatchObject({ code: 'LTX2_VENV_MISSING' });
+ expect((await failed).failure).toMatchObject({ classification: 'ltx2_venv_missing' });
+ } finally {
+ vi.mocked(existsSync).mockImplementation(originalExists);
+ }
+ });
+
it('emits a failed event naming the runtime venv when the child reports ModuleNotFoundError', async () => {
vi.resetModules();
const { spawnDetached } = await import('../../lib/detachedSpawn.js');
@@ -3621,6 +3639,44 @@ describe('generateVideo — signal-death diagnosis (#3101)', () => {
expect((await failed).error).toBe('Exit code 1: RuntimeError: shader compilation failed');
});
+ it('classifies distinct Metal abort evidence and leaves signal-only advice unclassified', async () => {
+ const failures = [];
+ for (const cause of ['OutOfMemory', 'InnocentVictim', null]) {
+ failures.push(await failWithSignal(`signal-evidence-${cause}`, 'SIGABRT', {
+ onStarted: (ctrl) => { if (cause) ctrl.emitStderr(`kIOGPUCommandBufferCallbackError${cause}\n`); },
+ }));
+ }
+ expect(failures[0].failure.cause).toBe('Metal command buffer failed: OutOfMemory');
+ expect(failures[1].failure.signature).not.toBe(failures[0].failure.signature);
+ expect(failures[2].failure).toBeNull();
+ });
+
+ it('preserves classified child failure evidence on a chained render', async () => {
+ vi.resetModules();
+ const { generateChainedVideo: chain } = await import('./local.js');
+ const { videoGenEvents: events } = await import('./events.js');
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const ctrl = makeSignalProc();
+ vi.mocked(spawnDetached).mockImplementationOnce(async () => {
+ setImmediate(() => {
+ ctrl.emitStderr("AttributeError: 'Tokenizer' object has no attribute 'encode'\n");
+ ctrl.fireClose(1, null);
+ });
+ return ctrl.proc;
+ });
+ const failed = new Promise((resolve) => {
+ const onFailed = (event) => {
+ if (event.generationId !== 'example-failed-chain') return;
+ events.off('failed', onFailed);
+ resolve(event);
+ };
+ events.on('failed', onFailed);
+ });
+ await chain({ chunks: 2, jobId: 'example-failed-chain', pythonPath: '/mock/python', modelId: 'ltx2_unified',
+ prompt: 'invented clip', width: 512, height: 512, numFrames: 25, fps: 24, mode: 'text' });
+ expect((await failed).failure).toMatchObject({ classification: 'attributeerror', signature: expect.stringMatching(/^[a-f0-9]{64}$/) });
+ });
+
it('SIGABRT names the macOS Metal command-buffer watchdog with a resolution/frame-count next step', async () => {
const evt = await failWithSignal('signal-sigabrt', 'SIGABRT');
expect(evt.error).toMatch(/Metal command-buffer watchdog/i);
diff --git a/server/services/videoGen/spawnWatch.js b/server/services/videoGen/spawnWatch.js
index 6225c52871..07a1ef0671 100644
--- a/server/services/videoGen/spawnWatch.js
+++ b/server/services/videoGen/spawnWatch.js
@@ -6,7 +6,7 @@ import { readFile } from 'fs/promises';
import { join } from 'path';
import { PATHS, rmGuarded } from '../../lib/fileUtils.js';
import { spawnDetached } from '../../lib/detachedSpawn.js';
-import { createVideoDiagnosticTail } from '../../lib/videoFailure.js';
+import { createVideoDiagnosticTail, normalizeVideoFailure } from '../../lib/videoFailure.js';
import { createLineReader } from '../../lib/streamLines.js';
import { claimHeavyLocalJob } from '../../lib/heavyJobClaim.js';
import { prepareLocalMemory, gpuBlockersMessage } from '../localMemory.js';
@@ -224,7 +224,7 @@ export async function spawnAndWatchVideo({
const reason = `Failed to spawn ${bin}: ${err.message}`;
console.log(`❌ Video generation spawn error [${jobId.slice(0, 8)}]: ${reason}`);
broadcastSse(job, { type: 'error', error: reason });
- videoGenEvents.emit('failed', { generationId: jobId, error: reason });
+ videoGenEvents.emit('failed', { generationId: jobId, error: reason, failure: normalizeVideoFailure(err, { prompts: [meta?.prompt, meta?.negativePrompt] }) });
videoJobState.activeProcess = null;
if (displaySlept) wakeDisplayForVideo(videoGenSettings, 'Video generation');
void releaseHeavyClaim();
@@ -353,6 +353,7 @@ export async function spawnAndWatchVideo({
if (code !== 0 && !watchdogSuccess) {
job.status = 'error';
let reason;
+ const failure = diagnostics.failure({ prompts: [meta?.prompt, meta?.negativePrompt] });
if (missingPyModule) {
const runtimeInfo = BYOV_RUNTIME_INFO[model.runtime];
if (runtimeInfo) {
@@ -373,12 +374,12 @@ export async function spawnAndWatchVideo({
fingerprint: await pickDeathFingerprint({ emitted: job.runtime, runtimeId: model.runtime }),
});
} else {
- const diagnostic = diagnostics.summary({ prompts: [meta?.prompt, meta?.negativePrompt] });
+ const diagnostic = failure?.summary || failure?.cause;
reason = `Exit code ${code}${diagnostic ? `: ${diagnostic}` : ''}`;
}
console.log(`❌ Video generation failed [${jobId.slice(0, 8)}]: ${reason}`);
broadcastSse(job, { type: 'error', error: `Generation failed: ${reason}` });
- videoGenEvents.emit('failed', { generationId: jobId, error: reason });
+ videoGenEvents.emit('failed', { generationId: jobId, error: reason, failure: missingPyModule ? normalizeVideoFailure(reason) : failure });
} else {
if (watchdogSuccess) {
console.log(`⚠️ video child force-killed (completion teardown hang) — output is intact [${jobId.slice(0, 8)}]`);
@@ -392,7 +393,7 @@ export async function spawnAndWatchVideo({
job.status = 'error';
console.error(`❌ Video close handler failed [${jobId.slice(0, 8)}]: ${err.message}`);
broadcastSse(job, { type: 'error', error: `Generation failed: ${err.message}` });
- videoGenEvents.emit('failed', { generationId: jobId, error: err.message });
+ videoGenEvents.emit('failed', { generationId: jobId, error: err.message, failure: normalizeVideoFailure(err, { prompts: [meta?.prompt, meta?.negativePrompt] }) });
} finally {
// A prompt-encode relaunch returns before this finalizer, deliberately
// leaving the display asleep while its replacement owns the GPU.
@@ -572,7 +573,7 @@ export async function spawnAndWatchVideo({
const reason = err.message || 'Video generation failed before the render child was wired';
console.log(`❌ Video generation setup error [${jobId.slice(0, 8)}]: ${reason}`);
broadcastSse(job, { type: 'error', error: reason });
- videoGenEvents.emit('failed', { generationId: jobId, error: reason });
+ videoGenEvents.emit('failed', { generationId: jobId, error: reason, failure: normalizeVideoFailure(err, { prompts: [meta?.prompt, meta?.negativePrompt] }) });
void cleanupTempFiles({ includeUploads: true, includeUntrackedAudio: true });
cleanupStepwisePreview();
closeJobAfterDelay(videoJobState.jobs, jobId);