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: align held video cohorts with runtime model selection (#6282)

[._.]/ Adam Eivyf2c6f7b8a52c
diff --git a/scripts/generate_fastvideo.py b/scripts/generate_fastvideo.py
index 0aead5a62a..8dff45c95a 100755
--- a/scripts/generate_fastvideo.py
+++ b/scripts/generate_fastvideo.py
@@ -123,7 +123,8 @@ 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):
+ if (re.match(r"^[\w.]*(?:Error|Exception):", line)
+ or re.search(r"\bkIOGPUCommandBufferCallbackError(?:OutOfMemory|InnocentVictim|Timeout|ImpactingInteractivity)\b", line)):
return line
if conversion:
return f"STATUS:{line}"
diff --git a/scripts/generate_fastvideo.test.js b/scripts/generate_fastvideo.test.js
index 3947301789..a8be2ba89b 100644
--- a/scripts/generate_fastvideo.test.js
+++ b/scripts/generate_fastvideo.test.js
@@ -20,7 +20,7 @@ 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) => {
+ it.each(['ValueError: loading converted tensors failed', 'kIOGPUCommandBufferCallbackErrorTimeout', 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',
@@ -42,7 +42,8 @@ describe.skipIf(!pyBin)('generate_fastvideo.py', () => {
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' });
+ if (cause?.startsWith('kIOGPU')) expect(tail.failure()).toMatchObject({ classification: 'metal-command-buffer', cause: 'Metal command buffer failed: Timeout' });
+ else if (cause) expect(tail.failure()).toMatchObject({ classification: 'valueerror', cause: 'loading converted tensors failed' });
else expect(tail.failure()).toBeNull();
});
diff --git a/server/lib/videoFailure.js b/server/lib/videoFailure.js
index bbbbe46208..8ca06d2108 100644
--- a/server/lib/videoFailure.js
+++ b/server/lib/videoFailure.js
@@ -9,12 +9,13 @@ const failureRecord = (classification, cause, identity = cause) => ({
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'),
+ signature: createHash('sha256').update(`${classification}\n${identity}`).digest('hex'),
});
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(?:proxy-)?authorization["']?\s*[:=][^\r\n]*/gi, '[credential]')
+ .replace(/\b(?:api[_-]?key|token|password|secret)["']?\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]')
diff --git a/server/lib/videoFailure.test.js b/server/lib/videoFailure.test.js
index b5afa43c94..c0276206c0 100644
--- a/server/lib/videoFailure.test.js
+++ b/server/lib/videoFailure.test.js
@@ -22,6 +22,10 @@ describe('local video diagnostic privacy boundary', () => {
expect(failure.cause.length).toBeLessThanOrEqual(240);
expect(normalizeVideoFailure('RuntimeError: authentication failed password="invented secret words"').cause)
.toBe('authentication failed [credential]');
+ const basic = Buffer.from('example:invented-password').toString('base64');
+ const basicFailure = normalizeVideoFailure(`RuntimeError: request failed Authorization: Basic ${basic}`);
+ expect(basicFailure.cause).toBe('request failed [credential]');
+ expect(basicFailure.signature).toBe(normalizeVideoFailure('RuntimeError: request failed Authorization: Basic changed').signature);
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/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index bc3b44a1df..afc4a00a6a 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -1024,6 +1024,11 @@ async function runJob(job) {
// corrupted path from a hand-edited media-jobs.json. Null it out here if
// it doesn't resolve under PATHS.uploads so the constraint holds end-to-end.
const safeParams = { ...job.params };
+ // Freeze only the dispatch copy to the default whose cohort passed the hold
+ // check. The retained job's original parameters stay unchanged.
+ if (job.videoCohort && (safeParams.modelId === undefined || safeParams.modelId === '')) {
+ safeParams.modelId = job.videoCohort.modelId;
+ }
if (safeParams.uploadedTempPath && (typeof safeParams.uploadedTempPath !== 'string' || !isUnderUploadsRoot(safeParams.uploadedTempPath))) {
console.log(`⚠️ media-job [${job.id.slice(0, 8)}] uploadedTempPath outside PATHS.uploads — nulled before gen invoke: ${safeParams.uploadedTempPath}`);
safeParams.uploadedTempPath = null;
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index 3ba9cb1aa8..da0c567cf1 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -38,9 +38,17 @@ vi.mock('../../lib/mediaModels.js', () => ({
getVideoModels: () => [
{ id: 'example-mlx', runtime: 'mlx_video' },
{ id: 'example-cuda', runtime: 'cuda_video' },
+ { id: 'example-large-cuda', runtime: 'cuda_video', hardwareRequirements: { requiresNvidiaGpu: true, minVramGb: 48 } },
{ id: 'example-other', runtime: 'mlx_video' },
],
- getDefaultVideoModelId: () => 'example-mlx',
+ getDefaultVideoModelId: vi.fn(() => 'example-mlx'),
+}));
+
+vi.mock('../../lib/systemCapabilities.js', async (importOriginal) => ({
+ ...await importOriginal(),
+ captureSystemCapabilities: () => ({ platform: 'win32', arch: 'x64', totalMemoryGb: 64 }),
+ detectSystemCapabilities: vi.fn(async () => ({ platform: 'win32', arch: 'x64', totalMemoryGb: 64,
+ cuda: { status: 'available', maxVramGb: 8 } })),
}));
// Mock the gen modules so the worker's dynamic imports return controllable
@@ -167,6 +175,8 @@ const remoteVideoMediaParams = () => ({
beforeEach(async () => {
tempDataDir = mkdtempSync(join(tmpdir(), 'mediaJobQueue-test-'));
Object.values(stubs).forEach((fn) => fn.mockReset());
+ const { getDefaultVideoModelId } = await import('../../lib/mediaModels.js');
+ getDefaultVideoModelId.mockImplementation(() => 'example-mlx');
// Default codex stub: hang (matches video/local defaults so tests that
// don't care about codex don't accidentally complete too fast).
stubs.generateImageCodex.mockImplementation(() => new Promise(() => {}));
@@ -1797,8 +1807,8 @@ describe('local video failure holds', () => {
});
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 errors = ["KeyError: 'Width'", "KeyError: 'width'", "KeyError: 'Width'",
+ "KeyError: 'width'", "KeyError: 'width'", "KeyError: 'width'"];
const ids = Array.from({ length: errors.length + 1 }, () => submit());
for (const [i, error] of errors.entries()) {
await tick();
@@ -1816,6 +1826,28 @@ describe('local video failure holds', () => {
expect(mediaJobQueue.listVideoHolds()).toEqual([]);
});
+ it('holds the effective CUDA fallback without rewriting omitted model parameters', async () => {
+ const { getDefaultVideoModelId } = await import('../../lib/mediaModels.js');
+ getDefaultVideoModelId.mockImplementation((capabilities) => capabilities?.cuda?.maxVramGb === 8
+ ? 'example-cuda' : 'example-large-cuda');
+ const ids = Array.from({ length: 4 }, () => mediaJobQueue.enqueueJob({
+ kind: 'video', params: { prompt: 'invented clip' },
+ }).jobId);
+ for (const id of ids.slice(0, 3)) {
+ await tick();
+ expect(stubs.generateVideo).toHaveBeenLastCalledWith(expect.objectContaining({ jobId: id, modelId: 'example-cuda' }));
+ await finish(id);
+ }
+ await tick();
+ expect(stubs.generateVideo).toHaveBeenCalledTimes(3);
+ const retained = mediaJobQueue.getJob(ids[3]);
+ expect(retained).toMatchObject({ status: 'queued', hold: { modelId: 'example-cuda', runtime: 'cuda_video' } });
+ expect(retained.params).not.toHaveProperty('modelId');
+ await mediaJobQueue.resumeVideoHold(retained.hold.id);
+ await tick();
+ expect(stubs.generateVideo).toHaveBeenLastCalledWith(expect.objectContaining({ jobId: ids[3], modelId: 'example-cuda' }));
+ });
+
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 a981ad7638..ca2ee26289 100644
--- a/server/services/mediaJobQueue/videoHolds.js
+++ b/server/services/mediaJobQueue/videoHolds.js
@@ -32,11 +32,16 @@ export function createVideoHolds() {
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 { getVideoModels } = await import('../../lib/mediaModels.js');
+ const omitted = (job) => job.params?.modelId === undefined || job.params?.modelId === '';
+ let defaultModel = null;
+ if (local.some(omitted)) {
+ const { resolveVideoModelSelection } = await import('../videoGen/modelSelection.js');
+ ({ model: defaultModel } = await resolveVideoModelSelection());
+ }
const models = getVideoModels();
for (const job of local) {
- const modelId = job.params?.modelId || getDefaultVideoModelId();
- const model = models.find((m) => m.id === modelId);
+ const model = omitted(job) ? defaultModel : models.find((m) => m.id === job.params.modelId);
job.videoCohort = model ? { modelId: model.id, runtime: model.runtime || 'mlx_video' } : null;
}
},
diff --git a/server/services/videoGen/generateVideo.js b/server/services/videoGen/generateVideo.js
index 4e561be921..72729d6043 100644
--- a/server/services/videoGen/generateVideo.js
+++ b/server/services/videoGen/generateVideo.js
@@ -25,12 +25,8 @@ import {
import { videoGenEvents } from './events.js';
import { broadcastSse, closeJobAfterDelay } from '../../lib/sseUtils.js';
import { getVideoModels, getDefaultVideoModelId, getTextEncoderRepo } from '../../lib/mediaModels.js';
-import {
- captureSystemCapabilities,
- detectSystemCapabilities,
- isHardwareCompatible,
- withHardwareCompatibility,
-} from '../../lib/systemCapabilities.js';
+import { isHardwareCompatible } from '../../lib/systemCapabilities.js';
+import { resolveVideoModelSelection } from './modelSelection.js';
import { findFfmpeg, findFfprobe } from '../../lib/ffmpeg.js';
import { inspectModelCache, findCachedRepoFile, findCachedRepoFiles } from '../../lib/hfCache.js';
import { safeChildProcessOptions } from '../../lib/processEnv.js';
@@ -162,27 +158,8 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// callers (legacy / tests) bypass the queue and would clobber the shared active process
// on concurrent calls; that's an explicit "don't do that" contract.
- const needsCuda = (requirements) => requirements?.requiresNvidiaGpu
- || requirements?.minVramGb != null
- || requirements?.minCudaComputeCapability != null;
- let capabilities = captureSystemCapabilities();
- // `undefined`/empty means the caller omitted the field and may use the
- // configured default. Explicit null is a routed-job sentinel and must remain
- // an unknown model so an older dispatcher cannot render a remote job locally.
- const modelWasOmitted = modelId === undefined || modelId === '';
- let selectedModelId = modelWasOmitted ? defaultVideoModelId(capabilities) : modelId;
- let resolvedModel = resolveVideoModel(selectedModelId);
- if (needsCuda(resolvedModel?.hardwareRequirements)) {
- capabilities = await detectSystemCapabilities();
- if (modelWasOmitted) selectedModelId = defaultVideoModelId(capabilities);
- resolvedModel = resolveVideoModel(selectedModelId);
- }
+ const { modelId: selectedModelId, model } = await resolveVideoModelSelection(modelId, { resolveModel: resolveVideoModel });
modelId = selectedModelId;
- const model = resolvedModel && withHardwareCompatibility(
- resolvedModel,
- capabilities,
- resolvedModel.hardwareRequirements,
- );
if (!model) throw new ServerError(`Unknown video model: ${modelId}`, { status: 400, code: 'VALIDATION_ERROR' });
if (!isHardwareCompatible(model.hardwareCompatibility)) {
throw new ServerError(
diff --git a/server/services/videoGen/modelSelection.js b/server/services/videoGen/modelSelection.js
new file mode 100644
index 0000000000..39e3c3177e
--- /dev/null
+++ b/server/services/videoGen/modelSelection.js
@@ -0,0 +1,24 @@
+import { getVideoModels, getDefaultVideoModelId } from '../../lib/mediaModels.js';
+import { captureSystemCapabilities, detectSystemCapabilities, withHardwareCompatibility } from '../../lib/systemCapabilities.js';
+
+// Queue admission and rendering must agree on a capability-dependent default.
+// Explicit null remains an unknown model: routed jobs use it as a sentinel.
+export async function resolveVideoModelSelection(modelId, {
+ resolveModel = (id) => getVideoModels().find((entry) => entry.id === id) || null,
+} = {}) {
+ const omitted = modelId === undefined || modelId === '';
+ let capabilities = captureSystemCapabilities();
+ let selectedModelId = omitted ? getDefaultVideoModelId(capabilities) : modelId;
+ let model = resolveModel(selectedModelId);
+ const requirements = model?.hardwareRequirements;
+ if (requirements?.requiresNvidiaGpu || requirements?.minVramGb != null
+ || requirements?.minCudaComputeCapability != null) {
+ capabilities = await detectSystemCapabilities();
+ if (omitted) selectedModelId = getDefaultVideoModelId(capabilities);
+ model = resolveModel(selectedModelId);
+ }
+ return {
+ modelId: selectedModelId,
+ model: model && withHardwareCompatibility(model, capabilities, model.hardwareRequirements),
+ };
+}