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: preserve converter causes and bound held model admission (#6282)

[._.]/ Adam Eivy7e37d3f10c0d
diff --git a/client/src/components/media/MediaJobsQueue.jsx b/client/src/components/media/MediaJobsQueue.jsx
index 706fdc11da..465e9201a1 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, resumeMediaVideoHold } from '../../services/apiMediaJobs.js';
+import { listMediaJobs, cancelMediaJob, cancelQueuedMediaJobs, deleteMediaJob, retryMediaJob, runMediaJobNow, listMediaVideoHolds, 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';
@@ -133,6 +133,7 @@ function modelLabel(params, renderer) {
// cards on the gen page already, so listing them here is duplicate noise.
export default function MediaJobsQueue({ kind, recentLimit = 10, className = '' }) {
const [jobs, setJobs] = useState([]);
+ const [holds, setHolds] = useState([]);
const [loading, setLoading] = useState(true);
const [hasSnapshot, setHasSnapshot] = useState(false);
const [loadError, setLoadError] = useState(false);
@@ -140,16 +141,20 @@ export default function MediaJobsQueue({ kind, recentLimit = 10, className = ''
const [resumingHold, setResumingHold] = useState(null);
const fetchJobs = useCallback(async () => {
- const outcome = await listMediaJobs(kind ? { kind } : {}).then(
+ const outcome = await Promise.all([
+ listMediaJobs(kind ? { kind } : {}),
+ !kind || kind === 'video' ? listMediaVideoHolds() : [],
+ ]).then(
(value) => ({ value }),
() => ({ error: true }),
);
- if (outcome.error || !Array.isArray(outcome.value)) {
+ if (outcome.error || !outcome.value.every(Array.isArray)) {
setLoadError(true);
setLoading(false);
return;
}
- setJobs(outcome.value);
+ setJobs(outcome.value[0]);
+ setHolds(outcome.value[1]);
setHasSnapshot(true);
setLoadError(false);
setLoading(false);
@@ -217,12 +222,12 @@ 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));
+ setHolds((previous) => previous.filter((hold) => hold.id !== id));
toast.success('Retained video jobs resumed');
fetchJobs();
})
diff --git a/client/src/components/media/MediaJobsQueue.test.jsx b/client/src/components/media/MediaJobsQueue.test.jsx
index f35c41587f..3db724b072 100644
--- a/client/src/components/media/MediaJobsQueue.test.jsx
+++ b/client/src/components/media/MediaJobsQueue.test.jsx
@@ -8,6 +8,7 @@ import { retypeSettled } from '../../test/settledInput';
const listMediaJobs = vi.fn();
const retryMediaJob = vi.fn();
const resumeMediaVideoHold = vi.fn();
+const listMediaVideoHolds = vi.fn();
vi.mock('../../services/apiMediaJobs.js', () => ({
listMediaJobs: (...a) => listMediaJobs(...a),
cancelMediaJob: vi.fn(),
@@ -16,6 +17,7 @@ vi.mock('../../services/apiMediaJobs.js', () => ({
retryMediaJob: (...a) => retryMediaJob(...a),
runMediaJobNow: vi.fn(),
resumeMediaVideoHold: (...a) => resumeMediaVideoHold(...a),
+ listMediaVideoHolds: (...a) => listMediaVideoHolds(...a),
}));
const getVideoGenStatus = vi.fn();
@@ -53,6 +55,8 @@ const trainingJob = {
beforeEach(() => {
listMediaJobs.mockReset();
+ listMediaVideoHolds.mockReset().mockResolvedValue([]);
+ resumeMediaVideoHold.mockReset();
listLoraTrainingCheckpoints.mockReset();
retryMediaJob.mockReset();
retryMediaJob.mockResolvedValue({ jobId: 'new-job-1234' });
@@ -713,6 +717,7 @@ describe('MediaJobsQueue — local video holds', () => {
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);
+ listMediaVideoHolds.mockResolvedValue([hold]);
resumeMediaVideoHold.mockRejectedValueOnce(new Error('Resume unavailable'));
const user = userEvent.setup();
render(<MediaJobsQueue kind="video" />);
@@ -727,9 +732,25 @@ describe('MediaJobsQueue — local video holds', () => {
expect(screen.getByRole('button', { name: 'Resuming…' })).toBeDisabled();
expect(screen.getByText('2 video jobs held')).toBeInTheDocument();
listMediaJobs.mockResolvedValue(jobs.map((job) => ({ ...job, hold: undefined })));
+ listMediaVideoHolds.mockResolvedValue([]);
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();
});
+
+ it('offers resume for an active hold after all retained jobs were canceled', async () => {
+ listMediaJobs.mockResolvedValue([]);
+ listMediaVideoHolds.mockResolvedValue([{ id: 'empty-hold', modelId: 'example-mlx', runtime: 'mlx_video',
+ cause: 'Shader compilation failed', heldJobCount: 0 }]);
+ const user = userEvent.setup();
+ render(<MediaJobsQueue kind="video" />);
+ expect(await screen.findByText('0 video jobs held')).toBeInTheDocument();
+ resumeMediaVideoHold.mockResolvedValue({ resumed: true });
+ listMediaVideoHolds.mockResolvedValue([]);
+ await user.click(screen.getByRole('button', { name: 'Resume' }));
+ await waitFor(() => expect(screen.queryByText('0 video jobs held')).not.toBeInTheDocument());
+ expect(resumeMediaVideoHold).toHaveBeenCalledWith('empty-hold', { silent: true });
+ expect(retryMediaJob).not.toHaveBeenCalled();
+ });
});
diff --git a/client/src/services/apiMediaJobs.js b/client/src/services/apiMediaJobs.js
index 32270b9df8..97c18e4e72 100644
--- a/client/src/services/apiMediaJobs.js
+++ b/client/src/services/apiMediaJobs.js
@@ -54,6 +54,9 @@ export const promptFromMedia = (data, options) => request('/media-jobs/prompt-fr
...options,
});
+// Holds outlive queued jobs, so status stays available when a batch is canceled.
+export const listMediaVideoHolds = (options = {}) => request('/media-jobs/holds', 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/scripts/generate_fastvideo.py b/scripts/generate_fastvideo.py
index d6f58afdb8..0aead5a62a 100755
--- a/scripts/generate_fastvideo.py
+++ b/scripts/generate_fastvideo.py
@@ -119,8 +119,14 @@ def advance_phase(line: str, current: str) -> str:
return phase
-def translate_line(line: str) -> str:
+def translate_line(line: str, *, conversion: bool = False) -> str:
"""Translate one upstream output line into PortOS's progress protocol."""
+ # Preserve terminal cause evidence before progress formatting can hide it.
+ # The queue deliberately ignores STATUS lines and generic child exit codes.
+ if re.match(r"^[\w.]*(?:Error|Exception):", line):
+ return line
+ if conversion:
+ return f"STATUS:{line}"
step_match = _DENOISE_STEP_PATTERN.search(line)
if step_match:
cur, total = int(step_match.group(1)), int(step_match.group(2))
@@ -257,7 +263,7 @@ def ensure_mlx_checkpoint(repo_dir: Path, model_root: Path, fmt: str, env: dict,
"--model-root", str(transformer),
"--out", str(out_base),
"--formats", fmt],
- env, repo_dir, lambda line: f"STATUS:{line}",
+ env, repo_dir, lambda line: translate_line(line, conversion=True),
)
if code != 0:
raise RuntimeError(f"FastH3 MLX conversion exited with code {code}")
diff --git a/scripts/generate_fastvideo.test.js b/scripts/generate_fastvideo.test.js
index 2f69289767..3947301789 100644
--- a/scripts/generate_fastvideo.test.js
+++ b/scripts/generate_fastvideo.test.js
@@ -3,6 +3,7 @@ import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { describe, expect, it } from 'vitest';
import { resolveTestPython } from '../server/lib/testHelper.js';
+import { createVideoDiagnosticTail } from '../server/lib/videoFailure.js';
const script = join(dirname(fileURLToPath(import.meta.url)), 'generate_fastvideo.py');
const pyBin = resolveTestPython();
@@ -19,6 +20,32 @@ const importRunner = [
].join('\n');
describe.skipIf(!pyBin)('generate_fastvideo.py', () => {
+ it.each(['ValueError: loading converted tensors failed', null])('preserves converter cause evidence (%s) without inventing it from an exit code', (cause) => {
+ const output = runPython(`${importRunner}\n${[
+ 'import tempfile',
+ 'from contextlib import redirect_stderr',
+ 'from unittest.mock import patch',
+ 'with tempfile.TemporaryDirectory() as tmp:',
+ ' root = Path(tmp)',
+ ' (root / "model" / "transformer").mkdir(parents=True)',
+ ' converter = root.joinpath(*runner._CONVERTER_SCRIPT)',
+ ' converter.parent.mkdir(parents=True)',
+ ' converter.touch()',
+ ' with patch.object(runner.subprocess, "Popen") as spawn, redirect_stderr(sys.stdout):',
+ ` spawn.return_value.stdout = ${JSON.stringify(['Loading weights', ...(cause ? [cause] : [])])}`,
+ ' spawn.return_value.wait.return_value = 1',
+ ' try:',
+ ' runner.ensure_mlx_checkpoint(root, root / "model", "int4", {}, root / "cache")',
+ ' except RuntimeError as error:',
+ ' print(f"❌ {error}")',
+ ].join('\n')}`);
+ expect(output).toContain('STATUS:Loading weights');
+ const tail = createVideoDiagnosticTail();
+ tail.push('stderr', output);
+ if (cause) expect(tail.failure()).toMatchObject({ classification: 'valueerror', cause: 'loading converted tensors failed' });
+ else expect(tail.failure()).toBeNull();
+ });
+
it('reports only denoising steps as render progress', () => {
const output = runPython(`${importRunner}\n${[
'print(runner.translate_line("Loading checkpoint: 100%|##########| 10/10"))',
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index e377c51fb9..a3f4f75c74 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -10559,6 +10559,14 @@
"server/routes/mediaJobs.js"
]
},
+ {
+ "method": "GET",
+ "path": "/api/media-jobs/holds",
+ "mountPath": "/api/media-jobs",
+ "sources": [
+ "server/routes/mediaJobs.js"
+ ]
+ },
{
"method": "POST",
"path": "/api/media-jobs/holds/:holdId/resume",
@@ -17618,8 +17626,8 @@
],
"stats": {
"mounts": 148,
- "operations": 2182,
- "declarations": 2190,
+ "operations": 2183,
+ "declarations": 2191,
"sourceFiles": 231
}
}
diff --git a/server/lib/videoFailure.js b/server/lib/videoFailure.js
index 684c8c5e7d..bbbbe46208 100644
--- a/server/lib/videoFailure.js
+++ b/server/lib/videoFailure.js
@@ -14,7 +14,7 @@ const failureRecord = (classification, cause, identity = cause) => ({
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]')
+ .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]')
@@ -50,8 +50,10 @@ export function normalizeVideoFailure(error, { prompts = [], code = error?.code
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;
+ if (!/[a-z0-9]/i.test(identity.replace(/\[[^\]]*\]/g, ''))) return null;
+ const display = identity.replace(/(['"])(?:\\.|(?!\1).)*?\1/g, '[value]').slice(0, MAX_CAUSE_LENGTH);
+ const cause = /[a-z]{3}/i.test(display.replace(/\[[^\]]*\]/g, ''))
+ ? display : `${classification}: redacted diagnostic details`;
return failureRecord(classification.toLowerCase().slice(0, 128), cause, identity);
}
diff --git a/server/lib/videoFailure.test.js b/server/lib/videoFailure.test.js
index 88a53477d7..b5afa43c94 100644
--- a/server/lib/videoFailure.test.js
+++ b/server/lib/videoFailure.test.js
@@ -20,6 +20,8 @@ describe('local video diagnostic privacy boundary', () => {
expect(failure.classification).toBe('runtimeerror');
expect(failure.cause).not.toMatch(/invented|private|mock|arbitrary|ghp_/);
expect(failure.cause.length).toBeLessThanOrEqual(240);
+ expect(normalizeVideoFailure('RuntimeError: authentication failed password="invented secret words"').cause)
+ .toBe('authentication failed [credential]');
expect(normalizeVideoFailure('RuntimeError: shape mismatch')).not.toEqual(normalizeVideoFailure('RuntimeError: shader compilation failed'));
expect(normalizeVideoFailure("ModuleNotFoundError: No module named 'example_runtime'"))
.toMatchObject({ classification: 'missing-module', cause: 'Python module example_runtime is missing' });
diff --git a/server/routes/mediaJobs.js b/server/routes/mediaJobs.js
index 76a3b01ef7..026dd09bed 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, resumeVideoHold, JOB_KINDS, JOB_STATUSES } from '../services/mediaJobQueue/index.js';
+import { listJobs, getJob, cancelJob, cancelQueuedJobs, enqueueJob, removeArchivedJob, runJobNow, listVideoHolds, 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';
@@ -131,6 +131,10 @@ router.post('/prompt-from-media', asyncHandler(async (req, res) => {
const resumeHoldParamsSchema = z.object({ holdId: z.string().uuid() });
const resumeHoldBodySchema = z.object({}).strict();
+router.get('/holds', asyncHandler(async (_req, res) => {
+ res.json(listVideoHolds());
+}));
+
router.post('/holds/:holdId/resume', asyncHandler(async (req, res) => {
const { holdId } = validateRequest(resumeHoldParamsSchema, req.params);
validateRequest(resumeHoldBodySchema, req.body ?? {});
diff --git a/server/routes/mediaJobs.test.js b/server/routes/mediaJobs.test.js
index 39595b854c..304957f8ab 100644
--- a/server/routes/mediaJobs.test.js
+++ b/server/routes/mediaJobs.test.js
@@ -14,6 +14,7 @@ const stubs = {
runJobNow: vi.fn(() => ({ ok: false, code: 'NOT_FOUND' })),
removeArchivedJob: vi.fn((id) => jobStore.delete(id)),
resumeVideoHold: vi.fn(),
+ listVideoHolds: vi.fn(() => []),
};
vi.mock('../services/mediaJobQueue/index.js', () => ({
JOB_KINDS: ['video', 'image'],
@@ -26,6 +27,7 @@ vi.mock('../services/mediaJobQueue/index.js', () => ({
runJobNow: (...args) => stubs.runJobNow(...args),
removeArchivedJob: (...args) => stubs.removeArchivedJob(...args),
resumeVideoHold: (...args) => stubs.resumeVideoHold(...args),
+ listVideoHolds: (...args) => stubs.listVideoHolds(...args),
}));
vi.mock('../services/videoGen/prepareParams.js', () => ({
validateVideoRetryParams: vi.fn(),
@@ -630,6 +632,10 @@ it('projects local holds on the array list and validates explicit resume', async
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);
+ jobStore.clear();
+ stubs.listVideoHolds.mockReturnValue([{ ...list.body[0].hold, heldJobCount: 0 }]);
+ const holds = await request(app).get('/api/media-jobs/holds');
+ expect(holds.body).toEqual([{ ...list.body[0].hold, heldJobCount: 0 }]);
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);
diff --git a/server/services/federatedMediaProvider.js b/server/services/federatedMediaProvider.js
index c45ad0faa4..d942663e3c 100644
--- a/server/services/federatedMediaProvider.js
+++ b/server/services/federatedMediaProvider.js
@@ -37,6 +37,7 @@ import {
enqueueJob,
getJob,
isRemoteMediaJob,
+ isVideoModelHeld,
laneConcurrencyFor,
listJobs,
} from './mediaJobQueue/index.js';
@@ -445,10 +446,11 @@ async function localGeneratorCapabilities(kind, pythonPath, { models, configured
: needsPython ? !!pythonPath
: kind === 'video' ? await isByovRuntimeReady(model?.runtime)
: true;
+ const held = kind === 'video' && model && isVideoModelHeld(model.id, model.runtime);
const reason = !isLocal ? 'unknown-engine'
: !model ? 'unknown-model'
: !modelSupportsInput ? 'unsupported-input'
- : !runtimeReady ? 'runtime-unavailable'
+ : !runtimeReady || held ? 'runtime-unavailable'
: !modelReady ? 'model-unavailable'
: null;
const frameStride = Number.isInteger(Number(model?.frameStride)) && Number(model.frameStride) >= 1 && Number(model.frameStride) <= 64
@@ -840,6 +842,13 @@ export async function submitFederatedMediaJob({ callerId, config, input, idempot
}
const inputAssetParams = await resolveSubmissionInputAssets({ callerId, input, capability });
+ // A local render may have failed while readiness/assets were being read.
+ // Refuse this cohort without transmitting its diagnostic or hold record.
+ if (input.kind === 'video' && isVideoModelHeld(capability._model.id, capability._model.runtime)) {
+ unavailable('Requested model is not currently available', 'MEDIA_PROVIDER_MODEL_UNAVAILABLE', 503, {
+ reason: 'runtime-unavailable',
+ });
+ }
// Opportunistic, and only once a submission has actually arrived: a provider
// nobody sends work to has nothing to sweep, and one that does gets swept on
// every admission. Never allowed to fail the job it rode in on.
diff --git a/server/services/federatedMediaProvider.test.js b/server/services/federatedMediaProvider.test.js
index 73876f2db2..30f905e129 100644
--- a/server/services/federatedMediaProvider.test.js
+++ b/server/services/federatedMediaProvider.test.js
@@ -12,6 +12,7 @@ const state = vi.hoisted(() => ({
cancelResult: { ok: true, status: 'canceled' },
imageModels: [],
videoModels: [],
+ videoHolds: [],
cachedRepos: new Set(),
laneWidthByKind: {},
}));
@@ -58,6 +59,7 @@ vi.mock('./musicEngineCapabilities.js', () => ({
vi.mock('./mediaJobQueue/index.js', () => ({
listJobs: vi.fn(() => state.jobs),
+ isVideoModelHeld: vi.fn((modelId, runtime = 'mlx_video') => state.videoHolds.some((hold) => hold.modelId === modelId && hold.runtime === runtime)),
// Widths deliberately differ per kind so a test can tell a minimum from a sum
// or a max; the real queue routes every federated kind to the same lane, but
// that is the thing under test, not a premise of it.
@@ -159,6 +161,7 @@ beforeEach(() => {
state.cancelResult = { ok: true, status: 'canceled' };
state.imageModels = [];
state.videoModels = [];
+ state.videoHolds = [];
state.cachedRepos = new Set();
state.laneWidthByKind = { audio: 1, image: 1, video: 1 };
__resetFederatedMediaProviderForTests();
@@ -588,6 +591,28 @@ describe('federated media provider — image/video kinds', () => {
});
});
+ it('refuses held video cohorts even with no retained jobs while admitting another model', async () => {
+ state.videoModels = ['held-video', 'ready-video'].map((id) => ({
+ id, name: id, runtime: 'ltx2', repo: `example/${id}`, supportedModes: ['text'],
+ }));
+ state.cachedRepos = new Set(state.videoModels.map((model) => model.repo));
+ const providerConfig = { ...config(), videoModels: state.videoModels.map(({ id }) => ({ engine: 'local', modelId: id })) };
+ state.videoHolds = [{ modelId: 'held-video', runtime: 'ltx2', cause: 'private diagnostic' }];
+ const status = await getFederatedMediaProviderStatus(providerConfig, { kinds: ['video'] });
+ expect(status.capabilities).toEqual([
+ expect.objectContaining({ modelId: 'held-video', ready: false, unavailableReason: 'runtime-unavailable' }),
+ expect.objectContaining({ modelId: 'ready-video', ready: true }),
+ ]);
+ expect(JSON.stringify(status)).not.toContain('private diagnostic');
+ await expect(submitFederatedMediaJob({ callerId: 'peer-example', config: providerConfig,
+ input: { kind: 'video', engine: 'local', modelId: 'held-video', prompt: 'an invented clip' }, idempotencyKey: 'held-video' }))
+ .rejects.toMatchObject({ code: 'MEDIA_PROVIDER_MODEL_UNAVAILABLE' });
+ expect(enqueueJob).not.toHaveBeenCalled();
+ const accepted = await submitFederatedMediaJob({ callerId: 'peer-example', config: providerConfig,
+ input: { kind: 'video', engine: 'local', modelId: 'ready-video', prompt: 'an invented clip' }, idempotencyKey: 'ready-video' });
+ expect(accepted.job).toMatchObject({ status: 'queued', kind: 'video' });
+ });
+
// These two models used to be hidden entirely: neither can render text-only,
// and the wire carried no conditioning for them to render FROM. Now that
// conditioning images cross (ADR
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index aa365c5dab..bc3b44a1df 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -649,9 +649,10 @@ function startLaneJob(job, { lane }) {
if (job.status === 'running') {
job.status = job.cancelRequested ? 'canceled' : 'failed';
videoHolds.captureFailure(job, err);
- job.error = `runJob threw: ${err.message}`;
+ job.error = job.cancelRequested ? 'Canceled' : `runJob threw: ${err.message}`;
job.completedAt = new Date().toISOString();
- broadcastSse(ensureSseEntry(job.id), { type: 'error', error: job.error });
+ 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);
}
@@ -1210,6 +1211,20 @@ export function enqueueJob({ kind, params, owner = null }) {
return { jobId: id, position: job.position, status: 'queued' };
}
+// Admission can query a cohort even after its last retained job is canceled.
+export function listVideoHolds() {
+ videoHolds.updateQueued(queue);
+ const counts = new Map();
+ for (const job of queue) {
+ if (job.hold) counts.set(job.hold.id, (counts.get(job.hold.id) || 0) + 1);
+ }
+ return videoHolds.snapshot().map((hold) => ({ ...hold, heldJobCount: counts.get(hold.id) || 0 }));
+}
+
+export function isVideoModelHeld(modelId, runtime) {
+ return videoHolds.has({ modelId, runtime: runtime || 'mlx_video' });
+}
+
// Resume retained work only; failed jobs are never re-enqueued.
export async function resumeVideoHold(holdId) {
if (!videoHolds.resume(holdId)) return false;
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index 52f4d9309b..3ba9cb1aa8 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -1723,6 +1723,7 @@ describe('local video failure holds', () => {
const persisted = JSON.parse(readFileSync(join(tempDataDir, 'media-jobs.json'), 'utf8'));
expect(persisted.videoHolds).toHaveLength(1);
expect(persisted.videoHolds[0]).not.toHaveProperty('signature');
+ expect(mediaJobQueue.isVideoModelHeld(modelId, persisted.videoHolds[0].runtime)).toBe(true);
vi.clearAllTimers();
mediaJobQueue.__resetForTests();
@@ -1733,6 +1734,7 @@ describe('local video failure holds', () => {
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(mediaJobQueue.isVideoModelHeld(modelId, persisted.videoHolds[0].runtime)).toBe(false);
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();
@@ -1794,6 +1796,26 @@ describe('local video failure holds', () => {
expect(mediaJobQueue.getJob(next).status).toBe('failed');
});
+ it('holds repeated quoted-only exceptions while keeping distinct keys separate', async () => {
+ const errors = ["KeyError: 'encoder_size'", "KeyError: 'decoder_size'", "KeyError: 'encoder_size'",
+ "KeyError: 'decoder_size'", "KeyError: 'decoder_size'", "KeyError: 'decoder_size'"];
+ const ids = Array.from({ length: errors.length + 1 }, () => submit());
+ for (const [i, error] of errors.entries()) {
+ await tick();
+ expect(mediaJobQueue.getJob(ids[i]).status).toBe('running');
+ await finish(ids[i], error);
+ }
+ await tick();
+ expect(mediaJobQueue.getJob(ids.at(-1))).toMatchObject({ status: 'queued',
+ hold: { classification: 'keyerror', cause: 'KeyError: redacted diagnostic details' } });
+ await mediaJobQueue.cancelJob(ids.at(-1));
+ const [hold] = mediaJobQueue.listVideoHolds();
+ expect(hold.heldJobCount).toBe(0);
+ expect(hold).not.toHaveProperty('signature');
+ expect(await mediaJobQueue.resumeVideoHold(hold.id)).toBe(true);
+ expect(mediaJobQueue.listVideoHolds()).toEqual([]);
+ });
+
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());
diff --git a/server/services/mediaJobQueue/videoHolds.js b/server/services/mediaJobQueue/videoHolds.js
index 1b22b6dd21..a981ad7638 100644
--- a/server/services/mediaJobQueue/videoHolds.js
+++ b/server/services/mediaJobQueue/videoHolds.js
@@ -26,6 +26,7 @@ export function createVideoHolds() {
for (const hold of z.array(videoHoldSchema).parse(value)) holds.set(cohortKey(hold), hold);
},
snapshot: () => [...holds.values()],
+ has: (cohort) => holds.has(cohortKey(cohort)),
clear() { holds.clear(); streaks.clear(); },
async resolveCohorts(jobs) {
const local = jobs.filter(isLocalVideo);
@@ -52,6 +53,7 @@ export function createVideoHolds() {
}
},
captureFailure(job, error, { code, failure } = {}) {
+ if (!isLocalVideo(job)) return;
job.videoFailure = failure !== undefined ? failure : normalizeVideoFailure(error, {
code, prompts: [job.params?.prompt, job.params?.negativePrompt, ...(job.params?.chunkPrompts || [])],
});