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: hold local video batches after repeated runtime failures (#6282)

[._.]/ Adam Eivyd6a179ff9f12
diff --git a/client/src/components/media/MediaJobsQueue.jsx b/client/src/components/media/MediaJobsQueue.jsx
index 0be8a275b5..706fdc11da 100644
--- a/client/src/components/media/MediaJobsQueue.jsx
+++ b/client/src/components/media/MediaJobsQueue.jsx
@@ -5,7 +5,7 @@ import toast from '../ui/Toast';
import ConfirmButtonPair from '../ui/ConfirmButtonPair';
import { FormField } from '../ui/FormField';
import AutoSizeTextarea from '../ui/AutoSizeTextarea';
-import { listMediaJobs, cancelMediaJob, cancelQueuedMediaJobs, deleteMediaJob, retryMediaJob, runMediaJobNow } from '../../services/apiMediaJobs.js';
+import { listMediaJobs, cancelMediaJob, cancelQueuedMediaJobs, deleteMediaJob, retryMediaJob, runMediaJobNow, resumeMediaVideoHold } from '../../services/apiMediaJobs.js';
import { listLoraTrainingCheckpoints } from '../../services/apiLoraTraining.js';
import { isCloudCliMode, IMAGE_GEN_MODE, CODEX_IMAGEGEN_DEFAULT_EFFORT, supportsCloudModelOverride, modeLabel, mediaJobLane, isCloudVideoMode } from '../../lib/imageGenBackends';
import { ANTIGRAVITY_CONFIGURED_DEFAULT, CODEX_EFFORT_LEVELS, isConfiguredDefaultModel } from '../../utils/providers';
@@ -137,6 +137,7 @@ export default function MediaJobsQueue({ kind, recentLimit = 10, className = ''
const [hasSnapshot, setHasSnapshot] = useState(false);
const [loadError, setLoadError] = useState(false);
const [showRecent, setShowRecent] = useState(false);
+ const [resumingHold, setResumingHold] = useState(null);
const fetchJobs = useCallback(async () => {
const outcome = await listMediaJobs(kind ? { kind } : {}).then(
@@ -216,6 +217,19 @@ export default function MediaJobsQueue({ kind, recentLimit = 10, className = ''
})
.catch((err) => toast.error(err?.message || 'Run-now failed'));
+ const holds = [...new Map(live.filter((job) => job.hold).map((job) => [job.hold.id, job.hold])).values()];
+ const handleResume = (id) => {
+ setResumingHold(id);
+ return resumeMediaVideoHold(id, { silent: true })
+ .then(() => {
+ setJobs((previous) => previous.map((job) => job.hold?.id === id ? { ...job, hold: undefined } : job));
+ toast.success('Retained video jobs resumed');
+ fetchJobs();
+ })
+ .catch((error) => toast.error(error?.message || 'Resume failed'))
+ .finally(() => setResumingHold(null));
+ };
+
const handleDelete = (id) => deleteMediaJob(id, { silent: true })
.then(() => {
setJobs((prev) => prev.filter((j) => j.id !== id));
@@ -275,6 +289,19 @@ export default function MediaJobsQueue({ kind, recentLimit = 10, className = ''
</div>
)}
+ {holds.map((hold) => (
+ <div key={hold.id} role="status" className="rounded border border-port-warning/30 bg-port-warning/10 p-3 text-sm">
+ <div className="font-medium text-port-warning">{hold.heldJobCount} video job{hold.heldJobCount === 1 ? '' : 's'} held</div>
+ <div className="text-xs text-port-text-muted break-words">{hold.modelId} · {hold.runtime}</div>
+ <p className="mt-1 break-words">{hold.cause}</p>
+ <p className="mt-1 text-xs text-port-text-muted">Three matching failures. Repair the runtime, then resume the retained jobs.</p>
+ <button type="button" disabled={resumingHold !== null} onClick={() => handleResume(hold.id)}
+ className="mt-2 min-h-[44px] rounded border border-port-border px-3 py-2 text-sm hover:bg-port-border disabled:opacity-50">
+ {resumingHold === hold.id ? 'Resuming…' : 'Resume'}
+ </button>
+ </div>
+ ))}
+
{loading && !hasSnapshot ? (
<div className="text-xs"><BrailleSpinner text="Loading…" /></div>
) : loadError && !hasSnapshot ? (
@@ -485,7 +512,7 @@ function JobRow({ job, onCancel, onRetry, onRunNow, onDelete }) {
</div>
</div>
<div className="flex items-center gap-2 shrink-0">
- <span className={`text-xs px-2 py-0.5 rounded ${STATUS_BADGE[job.status] || ''}`}>{job.status}</span>
+ <span className={`text-xs px-2 py-0.5 rounded ${STATUS_BADGE[job.status] || ''}`}>{job.hold ? 'held' : job.status}</span>
{job.cancelRequested && (
<span className="text-xs text-port-warning" title="Cancellation requested — waiting for worker">cancelling…</span>
)}
diff --git a/client/src/components/media/MediaJobsQueue.test.jsx b/client/src/components/media/MediaJobsQueue.test.jsx
index 3958160bb3..f35c41587f 100644
--- a/client/src/components/media/MediaJobsQueue.test.jsx
+++ b/client/src/components/media/MediaJobsQueue.test.jsx
@@ -7,6 +7,7 @@ import { retypeSettled } from '../../test/settledInput';
// the network. useAutoRefetch calls the fetcher on mount.
const listMediaJobs = vi.fn();
const retryMediaJob = vi.fn();
+const resumeMediaVideoHold = vi.fn();
vi.mock('../../services/apiMediaJobs.js', () => ({
listMediaJobs: (...a) => listMediaJobs(...a),
cancelMediaJob: vi.fn(),
@@ -14,6 +15,7 @@ vi.mock('../../services/apiMediaJobs.js', () => ({
deleteMediaJob: vi.fn(),
retryMediaJob: (...a) => retryMediaJob(...a),
runMediaJobNow: vi.fn(),
+ resumeMediaVideoHold: (...a) => resumeMediaVideoHold(...a),
}));
const getVideoGenStatus = vi.fn();
@@ -705,3 +707,29 @@ describe('MediaJobsQueue — video retry decode override (#5449)', () => {
expect(overrides.draftDecode).toBeNull();
});
});
+
+describe('MediaJobsQueue — local video holds', () => {
+ it('retains held state on a failed resume and clears it only after a successful response', async () => {
+ const hold = { id: 'example-hold', modelId: 'example-mlx', runtime: 'mlx_video', cause: 'Shader compilation failed', heldJobCount: 2 };
+ const jobs = ['held-1', 'held-2'].map((id) => ({ id, kind: 'video', status: 'queued', hold, params: {} }));
+ listMediaJobs.mockResolvedValue(jobs);
+ resumeMediaVideoHold.mockRejectedValueOnce(new Error('Resume unavailable'));
+ const user = userEvent.setup();
+ render(<MediaJobsQueue kind="video" />);
+ expect(await screen.findByText('2 video jobs held')).toBeInTheDocument();
+ expect(screen.getByText('Shader compilation failed')).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: 'Resume' }));
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Resume' })).toBeEnabled());
+ expect(screen.getByText('2 video jobs held')).toBeInTheDocument();
+ let finishResume;
+ resumeMediaVideoHold.mockImplementationOnce(() => new Promise((resolve) => { finishResume = resolve; }));
+ await user.click(screen.getByRole('button', { name: 'Resume' }));
+ expect(screen.getByRole('button', { name: 'Resuming…' })).toBeDisabled();
+ expect(screen.getByText('2 video jobs held')).toBeInTheDocument();
+ listMediaJobs.mockResolvedValue(jobs.map((job) => ({ ...job, hold: undefined })));
+ await act(async () => { finishResume({ resumed: true }); });
+ await waitFor(() => expect(screen.queryByText('2 video jobs held')).not.toBeInTheDocument());
+ expect(resumeMediaVideoHold).toHaveBeenLastCalledWith('example-hold', { silent: true });
+ expect(retryMediaJob).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/services/apiMediaJobs.js b/client/src/services/apiMediaJobs.js
index d2bb6b1885..32270b9df8 100644
--- a/client/src/services/apiMediaJobs.js
+++ b/client/src/services/apiMediaJobs.js
@@ -53,3 +53,7 @@ export const promptFromMedia = (data, options) => request('/media-jobs/prompt-fr
body: JSON.stringify(data),
...options,
});
+
+// Resume only the retained jobs covered by this local video hold.
+export const resumeMediaVideoHold = (holdId, options = {}) =>
+ request(`/media-jobs/holds/${encodeURIComponent(holdId)}/resume`, { method: 'POST', ...options });
diff --git a/data.reference/media-jobs.json b/data.reference/media-jobs.json
new file mode 100644
index 0000000000..f3cc54959b
--- /dev/null
+++ b/data.reference/media-jobs.json
@@ -0,0 +1,4 @@
+{
+ "jobs": [],
+ "videoHolds": []
+}
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index ac9e6a7ae4..d4082fdc7a 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -107,7 +107,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
**Examples.**
- Upload staging — `data/uploads/*`. Ephemeral; do not put in DB except as job references.
-- Media job queue — runtime queue state can stay file-backed short term, but **job history and artifact lineage are `db-primary`** and should move to the DB.
+- Media job queue — runtime queue state can stay file-backed short term, but **job history and artifact lineage are `db-primary`** and should move to the DB. Local video failure holds live in the existing `data/media-jobs.json` envelope as `videoHolds`, beside unchanged `jobs`. They are machine-local dispatch state, never federated and never sent in capability/status payloads to peers; the local queue API exposes them only on retained jobs. Three matching terminal causes hold one catalog model/runtime until explicit resume. Migration 343 adds an empty hold list to legacy envelopes without changing jobs; fresh installs use the empty seed. The envelope retains its existing filesystem backup coverage, with no new store, search index, sync cursor, or tombstone.
- Browser CDP profile / downloads — `data/browser-profile/`, `data/browser-downloads/` — cache, non-overridable backup excludes.
- Brain parity audit results — `data/brain_parity_reports.json` (`server/services/brainParity.js`, #4519). The last record-level brain-parity report per peer, keyed by peer `instanceId` (the same key `data/instances_sync_cursors.json` uses). `ephemeral-file` because it is a point-in-time *observation* about two installs, fully regenerable by re-running the audit, and stale the moment either side syncs — the durable state it describes lives in the brain stores. **Intentionally machine-local — never federated**: it is this install's view of a peer, and each peer computes its own. No sync cursor, no tombstone, no migration (an absent file reads as "nothing audited yet"). Per-type record lists are capped at 25 ids with a `truncated` flag so a badly diverged install can't grow the file without bound.
- CoS event ledgers — ordinary diagnostics use `data/cos/run-events.jsonl` + `run-events.1.jsonl`; persistent-mind trajectory uses the separate `mind-events.jsonl` + `mind-events.1.jsonl` pair (`server/services/agentRunEventLog.js`, #4540, #5082). Both are append-only, machine-local `ephemeral-file` replay aids with no federation cursor, tombstone, or `PORTOS_SCHEMA_VERSIONS` entry. The durable ordinary run record remains `data/runs/{id}/metadata.json`; mind rollups remain in their own bounded cache. Ordinary generations rotate at 5000 events and additionally expire after 30 days. Mind generations rotate at 10000 events without an age cutoff so a stopped mind keeps its unsummarized window, while high-volume mind chatter cannot evict ordinary run diagnostics. Migration 301 moves existing `mind.*` lines out of the shared files and stamps predecessor sequence provenance used to distinguish a legitimate timestamp jump from lost retained events. Payloads are redacted at append time, and both bounded pairs are backed up with the rest of `data/cos/`.
diff --git a/scripts/migrations/343-local-video-queue-holds.js b/scripts/migrations/343-local-video-queue-holds.js
new file mode 100644
index 0000000000..a86730816d
--- /dev/null
+++ b/scripts/migrations/343-local-video-queue-holds.js
@@ -0,0 +1,20 @@
+/** Add local runtime holds without changing or re-enqueueing any stored job. */
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+import { writeJsonAtomic } from './_lib.js';
+
+export default {
+ async up({ rootDir }) {
+ const file = join(rootDir, 'data', 'media-jobs.json');
+ const raw = await readFile(file, 'utf8').catch((error) => {
+ if (error.code === 'ENOENT') return null;
+ throw error;
+ });
+ if (raw === null) return { updated: 0 };
+ const envelope = JSON.parse(raw);
+ if (!envelope || !Array.isArray(envelope.jobs)) throw new Error('Invalid media jobs envelope');
+ if (Object.hasOwn(envelope, 'videoHolds')) return { updated: 0 };
+ await writeJsonAtomic(file, { ...envelope, videoHolds: [] });
+ return { updated: 1 };
+ },
+};
diff --git a/scripts/migrations/343-local-video-queue-holds.test.js b/scripts/migrations/343-local-video-queue-holds.test.js
new file mode 100644
index 0000000000..370f9f0fd4
--- /dev/null
+++ b/scripts/migrations/343-local-video-queue-holds.test.js
@@ -0,0 +1,24 @@
+import { afterEach, expect, it } from 'vitest';
+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import migration from './343-local-video-queue-holds.js';
+let rootDir;
+afterEach(async () => { if (rootDir) await rm(rootDir, { recursive: true, force: true }); });
+it('adds an empty hold list while preserving ordered jobs, unknown fields and existing holds', async () => {
+ rootDir = await mkdtemp(join(tmpdir(), 'video-holds-migration-'));
+ expect(await migration.up({ rootDir })).toEqual({ updated: 0 });
+ await mkdir(join(rootDir, 'data'));
+ const file = join(rootDir, 'data', 'media-jobs.json');
+ const legacy = { jobs: [{ id: 'example-job', params: { prompt: 'invented clip' } }], futureField: true };
+ await writeFile(file, JSON.stringify(legacy));
+ expect(await migration.up({ rootDir })).toEqual({ updated: 1 });
+ expect(JSON.parse(await readFile(file, 'utf8'))).toEqual({ ...legacy, videoHolds: [] });
+ const current = { ...legacy, videoHolds: [{ id: 'existing-hold' }] };
+ await writeFile(file, JSON.stringify(current));
+ expect(await migration.up({ rootDir })).toEqual({ updated: 0 });
+ expect(JSON.parse(await readFile(file, 'utf8'))).toEqual(current);
+ await writeFile(file, '{invalid');
+ await expect(migration.up({ rootDir })).rejects.toThrow();
+ expect(await readFile(file, 'utf8')).toBe('{invalid');
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 69ff2c2cdc..9c92f4c268 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -541,3 +541,5 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `runtimeEnv.js` | `isTestRunner()` — NODE_ENV=test **or** the VITEST env var, so a run that dropped NODE_ENV is still armed. Dependency-free and deliberately apart from `db.js`, which used to own it: the lowest-level file primitives need the same answer and must not pull in `pg`, and the many suites spelling `vi.mock('../lib/db.js', () => ({ query }))` used to strip it out of the graph for every other consumer. |
| `testDataIsolation.js` | Runtime backstop against a test WRITING into the install's real `data/` tree — the filesystem analogue of `db.js`'s row-write guard. `isInsideRealDataRoot(path)` canonicalizes a target through symlinked ancestors (it need not exist yet) and tests containment with `pathSafety.js#isPathAtOrInsideDir`, so a `..` climb, a relative path, a `data-archive` sibling, or a differently-cased spelling on a case-insensitive filesystem can't walk in sideways; the real root is re-derived through `dataRoot.js` rather than read from `PATHS`, so a suite that redirects `PATHS.data` to a temp root can't also redirect the guard. `assertNotRealDataWrite(path, operation)` throws under the test runner from `atomicWrite`, the guarded wrappers in `fileCore.js` (`writeFileGuarded`, `appendFileGuarded`, `copyFileGuarded`, `rmGuarded`, `unlinkGuarded`, `createWriteStreamGuarded`), and `collectionStore`'s record delete; `assertNotNewRealDataDir(dir)` is the create-only variant `ensureDir` uses, since `mkdir -p` on an existing directory mutates nothing. Inert outside the runner — the `isTestRunner()` check precedes every syscall. Services mutating files under `data/` route through these guarded wrappers. Closes the write half of the bug class `testDataIsolation.guards.test.js` covers statically and the two-run probe covers for reads (#6176, after #6171, #6203). |
| `testHelper.js` | Test helpers: `request()` (supertest-style HTTP) + `mockJsonResponse`/`mockTextResponse` (fetch `Response` mocks with `.text()`, `.json()`, and a `headers.get` content-type), `startLoopbackServer(app)`/`closeLoopbackServer(server)`/`waitForAbort(signal)` for tests that need a real socket (raw disconnects, SSE streaming) that `request()`'s run-to-completion fetch harness can't model, plus the source-scan pair `collectServerSources()` / `readServerSource(rel)` (and `SERVER_DIR`) used by the whole-tree guard suites — `spawnCwd.test.js` (#3193) and `cliChildEnv.test.js` (#3194). Those guards overlap deliberately, so they share one definition of "a source file"; change the ignore rules here and both move together. Cross-platform trio: `posixPath(v)` normalizes a RECEIVED path before comparing it to a POSIX-spelled literal (no-op on POSIX — never normalize the expectation, which would hide a genuinely wrong path), and `resolveTestPython()` returns an interpreter that actually runs, probing by execution because Windows ships a `python` Store-alias stub that exists but fails; `null` when there is none, for `describe.skipIf`; `pinPlatform(value)` pins `process.platform` and returns a restore that reinstates the ORIGINAL descriptor (deleting the pin when there was none) — it carries the one hazard every hand-rolled pin had to rediscover: never pin above an import that loads a native addon, which picks its prebuilt binary off the platform at load time (#4085). Python-shelling suites also take their two nested budgets from here: `PY_TEST_TIMEOUT_MS` (vitest per-test, passed as `it()`'s third argument — a real interpreter's wall time tracks machine load, not the assertion, so a ~4s case crosses the tight global 10s `testTimeout` on a contended full-suite worker) and the strictly smaller `PY_SUBPROCESS_TIMEOUT_MS` (every `execFileSync` spawn's own `timeout`, so a hung interpreter trips the spawn guard first and names the command instead of producing a bare vitest timeout; a subprocess allowance ABOVE the vitest budget is dead intent — vitest always wins). |
+
+| `videoFailure.js` | `normalizeVideoFailure` classifies and scrubs local video causes; `createVideoDiagnosticTail` retains bounded stdout/stderr diagnostics without grouping bare exit codes. |
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index 00b555f04b..e377c51fb9 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -10559,6 +10559,14 @@
"server/routes/mediaJobs.js"
]
},
+ {
+ "method": "POST",
+ "path": "/api/media-jobs/holds/:holdId/resume",
+ "mountPath": "/api/media-jobs",
+ "sources": [
+ "server/routes/mediaJobs.js"
+ ]
+ },
{
"method": "POST",
"path": "/api/media-jobs/prompt-from-media",
@@ -17610,8 +17618,8 @@
],
"stats": {
"mounts": 148,
- "operations": 2181,
- "declarations": 2189,
+ "operations": 2182,
+ "declarations": 2190,
"sourceFiles": 231
}
}
diff --git a/server/lib/index.js b/server/lib/index.js
index 047e677b9e..5914496e6f 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -515,3 +515,5 @@ export * from './dbTestGate.js';
export * from './runtimeEnv.js';
export * from './testDataIsolation.js';
export * from './testHelper.js';
+
+export * from './videoFailure.js';
diff --git a/server/lib/videoFailure.js b/server/lib/videoFailure.js
new file mode 100644
index 0000000000..2da1c69983
--- /dev/null
+++ b/server/lib/videoFailure.js
@@ -0,0 +1,68 @@
+/** Bounded, local-only video failure summaries shared by the runner and queue. */
+import { scrubSecretTokens } from './secretText.js';
+
+const MAX_TAIL_BYTES = 8192;
+const MAX_CAUSE_LENGTH = 240;
+
+// 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 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 (/Metal command-buffer watchdog|kIOGPUCommandBufferCallbackErrorImpactingInteractivity/.test(text)) {
+ return { classification: 'metal-watchdog', cause: 'Metal command-buffer watchdog stopped the render' };
+ }
+ if (/watchdog timeout: no runner output/.test(text)) {
+ return { classification: 'idle-timeout', cause: '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})` };
+ }
+ if (/python.*not configured/i.test(text)) {
+ return { classification: 'runtime-configuration', cause: '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);
+ if (!/[a-z]{3}/i.test(cause.replace(/\[[^\]]*\]/g, ''))) return null;
+ return { classification: exception[1].toLowerCase().slice(0, 128), cause };
+}
+
+export function createVideoDiagnosticTail() {
+ const tails = { stdout: Buffer.alloc(0), stderr: Buffer.alloc(0) };
+ return {
+ push(stream, chunk) {
+ 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.
+ 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}`;
+ }
+ }
+ return null;
+ },
+ };
+}
diff --git a/server/lib/videoFailure.test.js b/server/lib/videoFailure.test.js
new file mode 100644
index 0000000000..7ee98f0b48
--- /dev/null
+++ b/server/lib/videoFailure.test.js
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest';
+import { createVideoDiagnosticTail, normalizeVideoFailure } from './videoFailure.js';
+
+describe('local video diagnostic privacy boundary', () => {
+ it('rejects generic exits and progress, retaining only a bounded useful final cause', () => {
+ expect(normalizeVideoFailure('Exit code 1')).toBeNull();
+ const tail = createVideoDiagnosticTail();
+ 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();
+ tail.push('stderr', '\nRuntimeError: shader compilation failed');
+ expect(tail.summary()).toBe('RuntimeError: shader compilation failed');
+ });
+
+ it('scrubs conditioning, tokens, credentials and POSIX/Windows paths before identity or display', () => {
+ const token = `ghp_${'x'.repeat(30)}`;
+ const error = `RuntimeError: failure for invented private prompt at /mock/private/model and C:\\mock\\model token=arbitrary ${token}`;
+ const failure = normalizeVideoFailure(error, { prompts: ['invented private prompt'] });
+ expect(failure.classification).toBe('runtimeerror');
+ expect(failure.cause).not.toMatch(/invented|private|mock|arbitrary|ghp_/);
+ 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' });
+ });
+});
diff --git a/server/routes/mediaJobs.js b/server/routes/mediaJobs.js
index 1ab8022474..76a3b01ef7 100644
--- a/server/routes/mediaJobs.js
+++ b/server/routes/mediaJobs.js
@@ -9,7 +9,7 @@ import { Router } from 'express';
import { z } from 'zod';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
-import { listJobs, getJob, cancelJob, cancelQueuedJobs, enqueueJob, removeArchivedJob, runJobNow, JOB_KINDS, JOB_STATUSES } from '../services/mediaJobQueue/index.js';
+import { listJobs, getJob, cancelJob, cancelQueuedJobs, enqueueJob, removeArchivedJob, runJobNow, resumeVideoHold, JOB_KINDS, JOB_STATUSES } from '../services/mediaJobQueue/index.js';
import { refineMediaPrompt } from '../services/mediaPromptRefiner.js';
import { promptFromMedia } from '../services/mediaPromptFromMedia.js';
import { CODEX_EFFORT_LEVELS } from '../lib/providerModels.js';
@@ -129,6 +129,17 @@ router.post('/prompt-from-media', asyncHandler(async (req, res) => {
res.json(await promptFromMedia(data));
}));
+const resumeHoldParamsSchema = z.object({ holdId: z.string().uuid() });
+const resumeHoldBodySchema = z.object({}).strict();
+router.post('/holds/:holdId/resume', asyncHandler(async (req, res) => {
+ const { holdId } = validateRequest(resumeHoldParamsSchema, req.params);
+ validateRequest(resumeHoldBodySchema, req.body ?? {});
+ if (!await resumeVideoHold(holdId)) {
+ throw new ServerError('Hold no longer exists', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json({ resumed: true });
+}));
+
router.get('/:id', asyncHandler(async (req, res) => {
const job = getJob(req.params.id);
if (!job) {
diff --git a/server/routes/mediaJobs.test.js b/server/routes/mediaJobs.test.js
index 240b6a031a..39595b854c 100644
--- a/server/routes/mediaJobs.test.js
+++ b/server/routes/mediaJobs.test.js
@@ -13,6 +13,7 @@ const stubs = {
cancelQueuedJobs: vi.fn(async () => ({ canceled: 0 })),
runJobNow: vi.fn(() => ({ ok: false, code: 'NOT_FOUND' })),
removeArchivedJob: vi.fn((id) => jobStore.delete(id)),
+ resumeVideoHold: vi.fn(),
};
vi.mock('../services/mediaJobQueue/index.js', () => ({
JOB_KINDS: ['video', 'image'],
@@ -24,6 +25,7 @@ vi.mock('../services/mediaJobQueue/index.js', () => ({
cancelQueuedJobs: (...args) => stubs.cancelQueuedJobs(...args),
runJobNow: (...args) => stubs.runJobNow(...args),
removeArchivedJob: (...args) => stubs.removeArchivedJob(...args),
+ resumeVideoHold: (...args) => stubs.resumeVideoHold(...args),
}));
vi.mock('../services/videoGen/prepareParams.js', () => ({
validateVideoRetryParams: vi.fn(),
@@ -613,3 +615,26 @@ describe('POST /:id/retry — i2v reference mode overrides (#4874)', () => {
expect(stubs.enqueueJob).not.toHaveBeenCalled();
});
});
+
+it('projects local holds on the array list and validates explicit resume', async () => {
+ const holdId = '00000000-0000-4000-8000-000000000001';
+ jobStore.clear();
+ jobStore.set('held-job', { id: 'held-job', kind: 'video', status: 'queued', params: {}, hold: {
+ id: holdId, modelId: 'example-mlx', runtime: 'mlx_video', classification: 'runtimeerror',
+ cause: 'shader failed', heldAt: '2026-09-05T00:00:00.000Z', heldJobCount: 1, workerOnly: 'private',
+ } });
+ const app = makeApp();
+ const list = await request(app).get('/api/media-jobs');
+ expect(Array.isArray(list.body)).toBe(true);
+ expect(list.body[0]).toMatchObject({ status: 'queued', hold: { id: holdId, cause: 'shader failed', heldJobCount: 1 } });
+ expect(list.body[0].hold.workerOnly).toBeUndefined();
+ const detail = await request(app).get('/api/media-jobs/held-job');
+ expect(detail.body.hold).toEqual(list.body[0].hold);
+ stubs.resumeVideoHold.mockResolvedValue(true);
+ expect((await request(app).post(`/api/media-jobs/holds/${holdId}/resume`).send({})).body).toEqual({ resumed: true });
+ expect(stubs.resumeVideoHold).toHaveBeenLastCalledWith(holdId);
+ expect((await request(app).post('/api/media-jobs/holds/invalid/resume').send({})).status).toBe(400);
+ expect((await request(app).post(`/api/media-jobs/holds/${holdId}/resume`).send({ retry: true })).status).toBe(400);
+ stubs.resumeVideoHold.mockResolvedValue(false);
+ expect((await request(app).post(`/api/media-jobs/holds/${holdId}/resume`).send({})).status).toBe(404);
+});
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index 696d7fd07e..922244f004 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -47,6 +47,7 @@ import { getSettings } from '../settings.js';
import { IMAGE_GEN_MODE, CLOUD_IMAGE_GEN_MODES } from '../imageGen/modes.js';
import { VIDEO_GEN_MODE, CLOUD_VIDEO_GEN_MODES, mediaJobExecutionLane } from '../../lib/generationModes.js';
import { REMOTE_MEDIA_MODULES, isRemoteMediaJob } from './remoteMediaJob.js';
+import { createVideoHolds } from './videoHolds.js';
import { routedJobParams } from '../federatedMedia/routedJobParams.js';
// Cloud-CLI jobs (Codex/Grok/Agy images, Grok videos) share one parallel lane —
@@ -227,6 +228,7 @@ let running = null;
const cloudRunning = [];
const remoteRunning = [];
const archive = [];
+const videoHolds = createVideoHolds();
// One install can route to several peers, while each provider remains the
// authority on its own capacity. This bound prevents corrupted persisted state
@@ -433,7 +435,7 @@ async function persistImpl() {
const serializable = live.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 }),
);
- await atomicWrite(JOBS_FILE, { jobs: serializable });
+ await atomicWrite(JOBS_FILE, { jobs: serializable, videoHolds: videoHolds.snapshot() });
}
export async function initMediaJobQueue() {
@@ -459,6 +461,7 @@ export async function initMediaJobQueue() {
// indication that repairing or deleting one file restores it.
console.error(`❌ media-job queue: ${JOBS_FILE} is present but unreadable — starting empty and NOT persisting so it is preserved; repair or delete it and restart to re-enable persistence`);
}
+ videoHolds.restore(data?.videoHolds);
const persistedJobs = Array.isArray(data?.jobs) ? data.jobs : [];
const restartedFailedIds = [];
// #1332: training jobs whose detached trainer survived the restart, to be
@@ -565,6 +568,8 @@ export async function initMediaJobQueue() {
if (persistedJobs.length) {
console.log(`📦 mediaJobQueue restored: ${queue.length} queued, ${archive.length} archived`);
}
+ await videoHolds.resolveCohorts(queue);
+ videoHolds.updateQueued(queue);
// Pre-seed terminal SSE payloads for each restart-failed job so that any
// client that reconnects to /:jobId/events after a restart (the route
// attaches via attachSseClient → attachSse, which replays lastPayload)
@@ -650,6 +655,10 @@ function startLaneJob(job, { lane }) {
mediaJobEvents.emit('failed', job);
}
}
+ // Count once, after every terminal path (including pre-dispatch throws),
+ // and before releasing the lane. Boot reconciliation never comes here.
+ videoHolds.recordTerminal(job);
+ videoHolds.updateQueued(queue);
if (lane === 'cloud') {
const idx = cloudRunning.indexOf(job);
if (idx >= 0) cloudRunning.splice(idx, 1);
@@ -670,12 +679,16 @@ function startLaneJob(job, { lane }) {
async function drainLoop() {
while (true) {
+ const candidates = queue.slice();
+ await videoHolds.resolveCohorts(candidates);
+ videoHolds.updateQueued(queue);
// Single queue scan, promoting work independently into each open lane.
let gpuOpen = !running;
let cloudSlots = codexParallelLimit - cloudRunning.length;
let remoteSlots = REMOTE_MEDIA_PARALLEL_LIMIT - remoteRunning.length;
if ((gpuOpen || cloudSlots > 0 || remoteSlots > 0) && queue.length > 0) {
- for (const job of queue.slice()) {
+ for (const job of candidates) {
+ if (job.status !== 'queued' || job.hold) continue;
const lane = jobLane(job);
if (lane === 'remote') {
if (remoteSlots > 0) {
@@ -739,6 +752,7 @@ export function runJobNow(jobId) {
// /:jobId/events would keep showing the position from its original enqueue
// frame even after the line ahead of it cleared.
function recomputeQueuePositions() {
+ videoHolds.updateQueued(queue);
const cloudJobs = queue.filter(isCloudImageJob);
const remoteJobs = queue.filter(isRemoteMediaJob);
const gpuJobs = queue.filter((j) => jobLane(j) === 'gpu');
@@ -1192,6 +1206,14 @@ export function enqueueJob({ kind, params, owner = null }) {
return { jobId: id, position: job.position, status: 'queued' };
}
+// Resume retained work only; failed jobs are never re-enqueued.
+export async function resumeVideoHold(holdId) {
+ if (!videoHolds.resume(holdId)) return false;
+ videoHolds.updateQueued(queue);
+ await persist();
+ return true;
+}
+
// Bulk-cancel every queued job (optionally filtered by kind: 'image' | 'video').
// Running jobs are left alone — they have to be canceled individually with
// cancelJob(id) so the SIGTERM path runs. Returns the count of jobs that were
@@ -1351,6 +1373,7 @@ export function __resetForTests() {
cloudRunning.length = 0;
remoteRunning.length = 0;
archive.length = 0;
+ videoHolds.clear();
sseJobs.clear();
workerStarted = false;
initPromise = null;
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index 21cad4178c..2753b05702 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import { mkdtempSync, rmSync, writeFileSync, existsSync, readFileSync } from 'fs';
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync, existsSync, readFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { IMAGE_GEN_MODE } from '../imageGen/modes.js';
@@ -26,6 +26,7 @@ vi.mock('../../lib/fileUtils.js', async () => {
PATHS: new Proxy({}, {
get(_, key) {
if (key === 'data') return tempDataDir;
+ if (key === 'uploads' || key === 'videos') return join(tempDataDir, key);
return actual.PATHS[key];
},
}),
@@ -33,6 +34,15 @@ vi.mock('../../lib/fileUtils.js', async () => {
};
});
+vi.mock('../../lib/mediaModels.js', () => ({
+ getVideoModels: () => [
+ { id: 'example-mlx', runtime: 'mlx_video' },
+ { id: 'example-cuda', runtime: 'cuda_video' },
+ { id: 'example-other', runtime: 'mlx_video' },
+ ],
+ getDefaultVideoModelId: () => 'example-mlx',
+}));
+
// Mock the gen modules so the worker's dynamic imports return controllable
// stubs. The dispatcher relies on videoGenEvents / imageGenEvents to fire
// 'completed' or 'failed' for the worker to advance — we drive those events
@@ -311,6 +321,8 @@ describe('mediaJobQueue', () => {
expect(mediaJobQueue.listJobs({ kind: 'video' })).toHaveLength(2);
expect(mediaJobQueue.listJobs({ kind: 'image' })).toHaveLength(1);
expect(mediaJobQueue.listJobs({ owner: 'voice' })).toHaveLength(1);
+ await vi.dynamicImportSettled();
+ await flush();
// One job is 'running' (worker dequeued it), the other two are still 'queued'.
expect(mediaJobQueue.listJobs({ status: 'queued' })).toHaveLength(2);
expect(mediaJobQueue.listJobs({ status: 'running' })).toHaveLength(1);
@@ -1670,3 +1682,124 @@ describe('waitFor test helper (#5512)', () => {
.rejects.toThrow(/never became true within 20ms(?!.*last error)/s);
});
});
+
+// Regression: three terminal failures must preserve the rest of a batch,
+// including its staged bytes, across reload and explicit resume.
+describe('local video failure holds', () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => { vi.clearAllTimers(); vi.useRealTimers(); });
+
+ const tick = async () => {
+ await vi.dynamicImportSettled();
+ await vi.advanceTimersByTimeAsync(150);
+ await flush();
+ };
+ const submit = (modelId = 'example-mlx', extra = {}) => mediaJobQueue.enqueueJob({
+ kind: 'video', owner: 'example-owner', params: { modelId, prompt: 'invented clip', ...extra },
+ }).jobId;
+ const finish = async (id, error = 'RuntimeError: shader compilation failed') => {
+ videoGenEvents.emit(error ? 'failed' : 'completed', { generationId: id, error });
+ await flush();
+ };
+
+ it.each(['example-mlx', 'example-cuda'])('retains %s batch inputs through hold, restart and one resume', async (modelId) => {
+ const upload = join(tempDataDir, 'uploads', 'example.png');
+ mkdirSync(join(tempDataDir, 'uploads'));
+ writeFileSync(upload, 'synthetic image');
+ const ids = Array.from({ length: 5 }, () => submit(modelId, { uploadedTempPath: upload, seed: 42 }));
+ for (const id of ids.slice(0, 3)) {
+ await tick();
+ expect(mediaJobQueue.getJob(id).status).toBe('running');
+ await finish(id);
+ // A duplicate terminal event must never advance the streak a second time.
+ await finish(id);
+ }
+ await tick();
+ expect(stubs.generateVideo).toHaveBeenCalledTimes(3);
+ const retained = ids.slice(3).map((id) => mediaJobQueue.getJob(id));
+ expect(retained.map((j) => j.id)).toEqual(ids.slice(3));
+ expect(retained.every((j) => j.status === 'queued' && j.hold.heldJobCount === 2)).toBe(true);
+ expect(existsSync(upload)).toBe(true);
+ const persisted = JSON.parse(readFileSync(join(tempDataDir, 'media-jobs.json'), 'utf8'));
+ expect(persisted.videoHolds).toHaveLength(1);
+
+ vi.clearAllTimers();
+ mediaJobQueue.__resetForTests();
+ await importFresh();
+ await mediaJobQueue.initMediaJobQueue();
+ await tick();
+ expect(stubs.generateVideo).toHaveBeenCalledTimes(3);
+ const restored = mediaJobQueue.getJob(ids[3]);
+ expect(restored).toMatchObject({ owner: 'example-owner', status: 'queued', params: { uploadedTempPath: upload, seed: 42 }, hold: { heldJobCount: 2 } });
+ expect(await mediaJobQueue.resumeVideoHold(restored.hold.id)).toBe(true);
+ expect(await mediaJobQueue.resumeVideoHold(persisted.videoHolds[0].id)).toBe(false);
+ for (const id of ids.slice(3)) { await tick(); await finish(id, null); }
+ await tick();
+ expect(stubs.generateVideo.mock.calls.map(([p]) => p.jobId)).toEqual(ids);
+ expect(JSON.parse(readFileSync(join(tempDataDir, 'media-jobs.json'), 'utf8')).videoHolds).toEqual([]);
+ });
+
+ it('lets other local models, image, audio, training, cloud and remote work pass a hold', async () => {
+ const ids = Array.from({ length: 4 }, () => submit());
+ for (const id of ids.slice(0, 3)) { await tick(); await finish(id); }
+ const cloud = submit('example-mlx', { mode: 'grok' });
+ const remote = submit('example-mlx', { remoteMedia: remoteVideoMediaParams() });
+ const other = submit('example-other');
+ await tick();
+ expect(stubs.generateVideoGrok).toHaveBeenCalledWith(expect.objectContaining({ jobId: cloud }));
+ expect(stubs.generateVideoRemote).toHaveBeenCalledWith(expect.objectContaining({ jobId: remote }));
+ expect(mediaJobQueue.getJob(other).status).toBe('running');
+ await finish(other, null);
+ for (const [kind, emitter] of [['image', imageGenEvents], ['audio', audioGenEvents], ['training', (await import('../loraTraining/events.js')).trainingEvents]]) {
+ stubs.runTraining.mockResolvedValue({});
+ const { jobId } = mediaJobQueue.enqueueJob({ kind, params: {} });
+ await tick();
+ expect(mediaJobQueue.getJob(jobId).status).toBe('running');
+ emitter.emit('completed', { generationId: jobId });
+ await flush();
+ }
+ expect(mediaJobQueue.getJob(ids[3]).status).toBe('queued');
+ });
+
+ 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,
+ 'RuntimeError: shader failed', 'RuntimeError: shader failed', 'Exit code 1',
+ 'RuntimeError: shape mismatch', 'RuntimeError: shader failed', 'RuntimeError: shader failed'];
+ for (const error of errors) {
+ const id = submit(); await tick(); await finish(id, error);
+ }
+ const canceled = submit(); await tick();
+ await mediaJobQueue.cancelJob(canceled);
+ await finish(canceled, 'RuntimeError: unrelated cancellation');
+ const third = submit(); const retained = submit();
+ await tick(); await finish(third, 'RuntimeError: shader failed'); await tick();
+ expect(mediaJobQueue.getJob(canceled).status).toBe('canceled');
+ expect(mediaJobQueue.getJob(retained)).toMatchObject({ status: 'queued', hold: { cause: 'shader failed' } });
+ });
+
+ it('counts pre-dispatch rejection once and resumes with a cleared streak', async () => {
+ stubs.generateVideo.mockRejectedValue(new Error('Python is not configured'));
+ const ids = Array.from({ length: 4 }, () => submit());
+ for (let i = 0; i < 4; i += 1) await tick();
+ expect(stubs.generateVideo).toHaveBeenCalledTimes(3);
+ const held = mediaJobQueue.getJob(ids[3]);
+ expect(held.status).toBe('queued');
+ await mediaJobQueue.resumeVideoHold(held.hold.id);
+ const next = submit();
+ await tick(); await tick();
+ expect(stubs.generateVideo).toHaveBeenCalledTimes(5);
+ expect(mediaJobQueue.getJob(next).status).toBe('failed');
+ });
+
+ 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' } })),
+ { id: 'retained-legacy', kind: 'video', status: 'queued', params: { modelId: 'example-mlx' } },
+ ] }));
+ await mediaJobQueue.initMediaJobQueue(); await tick();
+ expect(mediaJobQueue.getJob('retained-legacy').status).toBe('running');
+ await finish('retained-legacy');
+ const next = submit(); await tick();
+ expect(mediaJobQueue.getJob(next).status).toBe('running');
+ });
+});
diff --git a/server/services/mediaJobQueue/sanitizeJob.js b/server/services/mediaJobQueue/sanitizeJob.js
index ef9f06553f..ba334a8ddb 100644
--- a/server/services/mediaJobQueue/sanitizeJob.js
+++ b/server/services/mediaJobQueue/sanitizeJob.js
@@ -1,4 +1,5 @@
import { effectiveJobPrompt } from '../../lib/federatedMediaWire.js';
+import { videoHoldSchema } from './videoHolds.js';
import { isRemoteMediaJob } from './remoteMediaJob.js';
import { mediaJobExecutionLane } from '../../lib/generationModes.js';
@@ -78,6 +79,7 @@ export function sanitizeJob(job) {
// requires an explicit `modelId` for a peer render) carries it on the wire
// request. This branch is now the ONLY source of a routed job's model id.
const routed = isRemoteMediaJob(job);
+ const hold = !routed && job.status === 'queued' ? videoHoldSchema.safeParse(job.hold) : null;
const remoteModelId = job.params?.remoteMedia?.request?.modelId;
if (safeParams && routed) {
if (remotePrompt) safeParams.prompt = remotePrompt;
@@ -99,6 +101,7 @@ export function sanitizeJob(job) {
executionLane: mediaJobExecutionLane({ kind: job.kind, mode: job.params?.mode, remote: routed }),
owner: job.owner,
status: job.status,
+ ...(hold?.success ? { hold: { ...hold.data, heldJobCount: job.hold.heldJobCount } } : {}),
queuedAt: job.queuedAt,
startedAt: job.startedAt,
completedAt: job.completedAt,
diff --git a/server/services/mediaJobQueue/videoHolds.js b/server/services/mediaJobQueue/videoHolds.js
new file mode 100644
index 0000000000..2b3d42eb7d
--- /dev/null
+++ b/server/services/mediaJobQueue/videoHolds.js
@@ -0,0 +1,79 @@
+/** Local video cohort circuit breaker; diagnostics never enter peer payloads. */
+import { randomUUID } from 'crypto';
+import { z } from 'zod';
+import { CLOUD_VIDEO_GEN_MODES } from '../../lib/generationModes.js';
+import { normalizeVideoFailure } from '../../lib/videoFailure.js';
+import { isRemoteMediaJob } from './remoteMediaJob.js';
+
+const cohortKey = ({ modelId, runtime }) => JSON.stringify([modelId, runtime]);
+const isLocalVideo = (job) => job.kind === 'video'
+ && !isRemoteMediaJob(job) && !CLOUD_VIDEO_GEN_MODES.includes(job.params?.mode);
+
+export const videoHoldSchema = z.object({
+ id: z.string().uuid(),
+ modelId: z.string().min(1).max(256),
+ runtime: z.string().min(1).max(128),
+ classification: z.string().min(1).max(128),
+ cause: z.string().min(1).max(240),
+ heldAt: z.string().datetime(),
+});
+
+export function createVideoHolds() {
+ const holds = new Map();
+ const streaks = new Map();
+ return {
+ restore(value = []) {
+ for (const hold of z.array(videoHoldSchema).parse(value)) holds.set(cohortKey(hold), hold);
+ },
+ snapshot: () => [...holds.values()],
+ clear() { holds.clear(); streaks.clear(); },
+ async resolveCohorts(jobs) {
+ const local = jobs.filter(isLocalVideo);
+ if (!local.length) return;
+ // Catalog loading stays off the queue's widely imported static graph.
+ const { getVideoModels, getDefaultVideoModelId } = await import('../../lib/mediaModels.js');
+ const models = getVideoModels();
+ for (const job of local) {
+ const modelId = job.params?.modelId || getDefaultVideoModelId();
+ const model = models.find((m) => m.id === modelId);
+ job.videoCohort = model ? { modelId: model.id, runtime: model.runtime || 'mlx_video' } : null;
+ }
+ },
+ updateQueued(jobs) {
+ const counts = new Map();
+ for (const job of jobs) {
+ const key = job.videoCohort && cohortKey(job.videoCohort);
+ if (isLocalVideo(job) && holds.has(key)) counts.set(key, (counts.get(key) || 0) + 1);
+ }
+ for (const job of jobs) {
+ const key = job.videoCohort && cohortKey(job.videoCohort);
+ job.hold = isLocalVideo(job) && holds.has(key)
+ ? { ...holds.get(key), heldJobCount: counts.get(key) } : undefined;
+ }
+ },
+ 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 || [])],
+ });
+ if (!failure) { streaks.delete(key); return; }
+ const signature = JSON.stringify([failure.classification, failure.cause.toLowerCase()]);
+ 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() });
+ }
+ },
+ resume(id) {
+ const entry = [...holds].find(([, hold]) => hold.id === id);
+ if (!entry) return false;
+ holds.delete(entry[0]);
+ streaks.delete(entry[0]);
+ return true;
+ },
+ };
+}
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index cbb80d96ee..0a8c059fed 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -3603,6 +3603,24 @@ describe('generateVideo — signal-death diagnosis (#3101)', () => {
return failed;
}
+ it.each(['stdout', 'stderr'])('keeps a chunked final %s exception in the ordinary exit cause', async (stream) => {
+ vi.resetModules();
+ const { generateVideo: gv } = 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 () => ctrl.proc);
+ const failed = new Promise((resolve) => events.once('failed', resolve));
+ await gv({ jobId: 'example-diagnostic', pythonPath: '/mock/python', modelId: 'ltx2_unified',
+ prompt: 'invented clip', width: 512, height: 512, numFrames: 25, fps: 24, mode: 'text' });
+ const emit = stream === 'stdout' ? ctrl.emitStdout : ctrl.emitStderr;
+ emit('Traceback (most recent call last):\n File "/mock/runtime.py", line 42, in render\n');
+ emit('RuntimeError: shader comp');
+ emit('ilation failed');
+ await ctrl.fireClose(1, null);
+ expect((await failed).error).toBe('Exit code 1: RuntimeError: shader compilation failed');
+ });
+
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 74881f307d..6225c52871 100644
--- a/server/services/videoGen/spawnWatch.js
+++ b/server/services/videoGen/spawnWatch.js
@@ -6,6 +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 { createLineReader } from '../../lib/streamLines.js';
import { claimHeavyLocalJob } from '../../lib/heavyJobClaim.js';
import { prepareLocalMemory, gpuBlockersMessage } from '../localMemory.js';
@@ -244,8 +245,9 @@ export async function spawnAndWatchVideo({
// grow it without limit; the abort banner is the last thing printed before
// the process dies, so the tail always holds it.
const stderrTail = [];
+ const diagnostics = createVideoDiagnosticTail();
const recordStderrTail = (raw) => {
- stderrTail.push(raw);
+ stderrTail.push(raw.slice(-2048));
if (stderrTail.length > STDERR_TAIL_LINES) stderrTail.shift();
};
@@ -291,10 +293,12 @@ export async function spawnAndWatchVideo({
}, { splitRe: /[\n\r]+/ });
proc.stdout.on('data', (chunk) => {
+ diagnostics.push('stdout', chunk);
stdoutReader.push(chunk);
});
proc.stderr.on('data', (chunk) => {
+ diagnostics.push('stderr', chunk);
stderrReader.push(chunk);
});
@@ -369,7 +373,8 @@ export async function spawnAndWatchVideo({
fingerprint: await pickDeathFingerprint({ emitted: job.runtime, runtimeId: model.runtime }),
});
} else {
- reason = `Exit code ${code}`;
+ const diagnostic = diagnostics.summary({ prompts: [meta?.prompt, meta?.negativePrompt] });
+ reason = `Exit code ${code}${diagnostic ? `: ${diagnostic}` : ''}`;
}
console.log(`❌ Video generation failed [${jobId.slice(0, 8)}]: ${reason}`);
broadcastSse(job, { type: 'error', error: `Generation failed: ${reason}` });