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: SIGKILL local video render that stalls before any output (#2198)

[._.]/ Adam Eivyf4d8abc6eba0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index d5ca0c2538..afc1923ded 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -48,6 +48,7 @@
- **[issue-2036] Sketch & Annotation Canvas (phase 2): re-render an image guided by your annotations.** The annotate page (`/media/annotate/:mediaKey`) gained a "Re-render" action: draw over a generated image, then feed your markup back through local img2img so the marks reshape the render. A confirmation dialog names the exact local model it will run (no surprise AI calls) and lets you add an optional prompt and tune how much to change before it starts; the new render is queued and appears in Media History. Requires a local FLUX img2img runner — the action explains when one isn't available. Phase 3 (blank-canvas storyboard) remains open on #2036.
- **[issue-2196] Video Gen now takes an exact custom Width×Height.** The `/media/video` page only offered a 9-item resolution preset dropdown, so a size the presets didn't cover was only reachable via URL params, remix/continue, or aspect-snap on upload. Two numeric Width and Height inputs now sit beside the preset select — type any dimensions and the render uses them (the server still rounds each down to a multiple of 64 and enforces the per-tier pixel budget). Uploading a source image still auto-snaps the size to the image's aspect ratio by default, until you take the dimensions into your own hands.
- **[issue-2197] First-run model downloads now show GB progress instead of raw text.** The video and image generation handlers now parse byte sizes from `DOWNLOAD:` markers and tqdm progress bars, displaying a formatted "Downloading model · first run · X.X GB / Y.Y GB" message instead of the raw protocol output. Progress frames include `downloadedBytes`/`totalBytes` numeric fields so the UI can build download progress bars. Phase tracking (`isDownloading`, `currentPhase`) ensures the formatting only applies during actual download phases.
+- **[issue-2198] A wedged local video render that produces no output is now killed automatically instead of pinning the GPU queue.** The existing completion watchdog only guards a render that finishes and then hangs in teardown — it never armed for a render that stalls *before emitting anything* (a known MLX/Metal failure mode where the job never exits and never prints), which held the serialized GPU lane until you manually canceled. A new idle-stall deadline arms at spawn and resets on every child output line (stdout or stderr); if a render produces no output for a generous window (default 10 minutes, tunable via `VIDEOGEN_IDLE_STALL_MS`) it's SIGKILLed and surfaced as a failed job, so the next queued render can start. The window is deliberately generous so a legitimately slow first-token render (weights load + Metal kernel compile) is never killed, and a manual cancel still works and always wins. (`server/services/videoGen/local.js`)
## MeatSpace POST
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index bee2afa137..c4633d82e4 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -82,6 +82,30 @@ const COMPLETION_WATCHDOG_GRACE_MS = (() => {
return Number.isFinite(raw) && raw > 0 ? raw : 40000;
})();
+// Pre-output idle-stall deadline (defense against a render that wedges BEFORE
+// emitting anything).
+//
+// The completion watchdog above only arms once a completion marker/result JSON
+// reaches stdout — it guards a post-completion teardown hang, NOT a render that
+// stalls before producing any output (a known MLX/Metal failure mode where a
+// job never exits and never prints). Left alone, that pins the serialized GPU
+// lane (mediaJobQueue) until a manual cancel. This idle timer is armed at spawn
+// and RESET on every child output line; if it fires it SIGKILLs the child, and
+// the 'close' handler surfaces the timeout as a FAILED job so the lane frees for
+// the next queued render. A manual cancel still works and always wins.
+//
+// The window is deliberately generous — a big model's first-token render can
+// spend minutes loading weights + compiling Metal kernels before its first
+// progress line, and we must never kill a legitimately-slow render. Sentinel +
+// validate: a missing/non-numeric/non-positive VIDEOGEN_IDLE_STALL_MS falls back
+// to the default (10 min) instead of collapsing to 0/NaN. Set it to 0 or a
+// negative value only by editing the code path — the env knob can only raise or
+// lower a positive window, never disable the guard silently.
+const IDLE_STALL_DEADLINE_MS = (() => {
+ const raw = parseInt(process.env.VIDEOGEN_IDLE_STALL_MS || '', 10);
+ return Number.isFinite(raw) && raw > 0 ? raw : 600000; // 10 minutes of no output
+})();
+
// Upstream prints this when the final decode+mux finishes, just before it should
// exit. Matching it (case-insensitive) lets us arm the watchdog even for
// runtimes that don't emit the result JSON on stdout.
@@ -877,6 +901,49 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
if (typeof completionWatchdog.unref === 'function') completionWatchdog.unref();
};
+ // Pre-output idle-stall deadline. Armed at spawn and reset on every child
+ // output line (stdout OR stderr — a render loading weights logs to stderr via
+ // loguru/tqdm well before any stdout progress). If it fires, the render has
+ // produced NO output for the whole generous window — treat it as wedged,
+ // SIGKILL it, and let the 'close' handler surface a failed job so the
+ // serialized GPU lane frees. Cleared in every terminal path alongside the
+ // completion watchdog so it can't fire against a recycled PID.
+ let idleStallTimer = null;
+ // Set when THIS timer fires the SIGKILL so the 'close' handler reports a
+ // clear "stalled — no output" reason instead of the generic "killed, likely
+ // OOM" message a bare SIGKILL would otherwise produce.
+ let idleStallFired = false;
+ const clearIdleStallTimer = () => {
+ if (idleStallTimer) {
+ clearTimeout(idleStallTimer);
+ idleStallTimer = null;
+ }
+ };
+ const armIdleStallTimer = () => {
+ idleStallTimer = setTimeout(() => {
+ // Outside the Express request lifecycle — guard so an uncaught throw
+ // can't crash the Node process.
+ try {
+ idleStallTimer = null;
+ if (activeProcess !== proc || proc.exitCode !== null || proc.signalCode !== null) return;
+ console.log(`⚠️ video child produced no output for ${IDLE_STALL_DEADLINE_MS}ms — stalled, SIGKILL [${jobId.slice(0, 8)}]`);
+ idleStallFired = true;
+ proc.kill('SIGKILL');
+ } catch (err) {
+ console.error(`❌ idle-stall watchdog failed [${jobId.slice(0, 8)}]: ${err.message}`);
+ }
+ }, IDLE_STALL_DEADLINE_MS);
+ if (typeof idleStallTimer.unref === 'function') idleStallTimer.unref();
+ };
+ // Every output line means the render is alive — restart the countdown.
+ const resetIdleStallTimer = () => {
+ clearIdleStallTimer();
+ armIdleStallTimer();
+ };
+ // Arm immediately: the highest-risk stall is a job that never emits its FIRST
+ // line (weights load / kernel compile hangs), so the clock starts at spawn.
+ armIdleStallTimer();
+
// Hold a sleep-prevention lock for the lifetime of the python child, so a
// 90s+ render doesn't get aborted by sleep on a laptop. `-s` blocks system
// sleep (lid-close / low-power), `-i` blocks idle sleep, `-d` blocks display
@@ -891,6 +958,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// crash the server with an unhandled error event.
proc.on('error', (err) => {
clearCompletionWatchdog();
+ clearIdleStallTimer();
job.status = 'error';
const reason = `Failed to spawn ${bin}: ${err.message}`;
console.log(`❌ Video generation spawn error [${jobId.slice(0, 8)}]: ${reason}`);
@@ -924,6 +992,9 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
const handleLine = makeVideoGenLineHandler({ job, jobId, pythonNoiseRe: PYTHON_NOISE_RE });
proc.stdout.on('data', (chunk) => {
+ // Any output proves the render is progressing — restart the idle-stall
+ // countdown before parsing so a slow-but-alive render is never killed.
+ resetIdleStallTimer();
outputBuf += chunk.toString();
const lines = outputBuf.split('\n');
outputBuf = lines.pop();
@@ -950,6 +1021,9 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
});
proc.stderr.on('data', (chunk) => {
+ // Weight-load / kernel-compile progress often streams to stderr (loguru,
+ // tqdm) long before the first stdout line — count it as liveness too.
+ resetIdleStallTimer();
for (const raw of chunk.toString().split(/[\n\r]+/)) {
// Record the root-cause module only — downstream imports in the same
// traceback raise the same error against later names.
@@ -963,6 +1037,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
proc.on('close', async (code, signal) => {
clearCompletionWatchdog();
+ clearIdleStallTimer();
activeProcess = null;
// Wrap the whole teardown so a throw from finalizeGeneratedVideo (history
// save, thumbnail, file move) can't leak as an unhandled rejection — on
@@ -1008,6 +1083,11 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
} else {
reason = `Python module '${missingPyModule}' is missing. Install it into the configured Python environment and retry.`;
}
+ } else if (idleStallFired) {
+ // Distinguish a stall-kill from a real OOM kill — both arrive as
+ // SIGKILL, but this one means the render produced NO output for the
+ // whole idle window and we terminated it to free the GPU lane.
+ reason = `Render stalled — no output for ${Math.round(IDLE_STALL_DEADLINE_MS / 1000)}s; terminated to free the GPU queue (raise VIDEOGEN_IDLE_STALL_MS if this was a legitimately slow render)`;
} else if (signal === 'SIGKILL') {
reason = 'Process killed (likely out of memory — try a smaller model or resolution)';
} else if (signal) {
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index 9656acd88a..501e86afe7 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -872,6 +872,238 @@ describe('generateVideo — panel-side completion watchdog', () => {
});
});
+describe('generateVideo — pre-output idle-stall deadline', () => {
+ // Same hanging-proc harness as the completion-watchdog suite, but here the
+ // render never emits its completion marker — it wedges before (or between)
+ // output, which the completion watchdog does NOT cover.
+ function makeHangingProc() {
+ const listeners = {};
+ let stdoutData = null;
+ let stderrData = null;
+ const proc = {
+ pid: 7373,
+ exitCode: null,
+ signalCode: null,
+ killed: false,
+ stdout: { on: vi.fn((event, fn) => { if (event === 'data') stdoutData = fn; }) },
+ stderr: { on: vi.fn((event, fn) => { if (event === 'data') stderrData = fn; }) },
+ on(event, fn) { listeners[event] = fn; return proc; },
+ kill: vi.fn((signal) => { proc.killed = true; proc.signalCode = signal; }),
+ };
+ return {
+ proc,
+ emitStdout: (text) => stdoutData?.(Buffer.from(text)),
+ emitStderr: (text) => stderrData?.(Buffer.from(text)),
+ fireClose: (code, signal) => listeners.close?.(code, signal),
+ };
+ }
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ delete process.env.VIDEOGEN_IDLE_STALL_MS;
+ });
+
+ it('SIGKILLs a render that never produces any output within the idle window', async () => {
+ process.env.VIDEOGEN_IDLE_STALL_MS = '60000';
+ vi.resetModules();
+ ({ generateVideo } = await import('./local.js'));
+
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const hang = makeHangingProc();
+ vi.mocked(spawnDetached).mockImplementationOnce(async () => hang.proc);
+
+ generateVideo({
+ jobId: 'idle-stall-no-output',
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx2_unified',
+ prompt: 'wedge before any output',
+ width: 512, height: 512, numFrames: 25, fps: 24,
+ mode: 'text',
+ });
+ await vi.advanceTimersByTimeAsync(0);
+
+ // Just before the deadline: still alive.
+ await vi.advanceTimersByTimeAsync(59999);
+ expect(hang.proc.kill).not.toHaveBeenCalled();
+
+ // Past the deadline with zero output: the idle-stall timer SIGKILLs it.
+ await vi.advanceTimersByTimeAsync(2);
+ expect(hang.proc.kill).toHaveBeenCalledWith('SIGKILL');
+ });
+
+ it('resets the idle timer on each output line so a slow-but-alive render is not killed', async () => {
+ process.env.VIDEOGEN_IDLE_STALL_MS = '60000';
+ vi.resetModules();
+ ({ generateVideo } = await import('./local.js'));
+
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const hang = makeHangingProc();
+ vi.mocked(spawnDetached).mockImplementationOnce(async () => hang.proc);
+
+ generateVideo({
+ jobId: 'idle-stall-slow-alive',
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx2_unified',
+ prompt: 'slow but steady',
+ width: 512, height: 512, numFrames: 25, fps: 24,
+ mode: 'text',
+ });
+ await vi.advanceTimersByTimeAsync(0);
+
+ // Emit an output line every 40s (well inside the 60s window) five times —
+ // each resets the countdown, so the render is never killed even though the
+ // total elapsed time (200s) far exceeds one window.
+ for (let i = 0; i < 5; i++) {
+ // eslint-disable-next-line no-await-in-loop
+ await vi.advanceTimersByTimeAsync(40000);
+ hang.emitStdout(`STAGE:render:step:${i}:30:rendering\n`);
+ expect(hang.proc.kill).not.toHaveBeenCalled();
+ }
+ // …but once output stops, the window elapses and it IS killed.
+ await vi.advanceTimersByTimeAsync(60001);
+ expect(hang.proc.kill).toHaveBeenCalledWith('SIGKILL');
+ });
+
+ it('counts a stderr line (weight-load/kernel-compile progress) as liveness', async () => {
+ process.env.VIDEOGEN_IDLE_STALL_MS = '60000';
+ vi.resetModules();
+ ({ generateVideo } = await import('./local.js'));
+
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const hang = makeHangingProc();
+ vi.mocked(spawnDetached).mockImplementationOnce(async () => hang.proc);
+
+ generateVideo({
+ jobId: 'idle-stall-stderr-liveness',
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx2_unified',
+ prompt: 'stderr keeps it alive',
+ width: 512, height: 512, numFrames: 25, fps: 24,
+ mode: 'text',
+ });
+ await vi.advanceTimersByTimeAsync(0);
+
+ await vi.advanceTimersByTimeAsync(40000);
+ hang.emitStderr('Fetching 12 files: 40%|████ | 5/12\n');
+ // The stderr line reset the timer, so 40s later (80s total) it's still alive.
+ await vi.advanceTimersByTimeAsync(40000);
+ expect(hang.proc.kill).not.toHaveBeenCalled();
+ });
+
+ it('surfaces a stall-kill as a FAILED job (frees the GPU lane) with a stall-specific reason', async () => {
+ process.env.VIDEOGEN_IDLE_STALL_MS = '60000';
+ vi.resetModules();
+ ({ generateVideo } = await import('./local.js'));
+ ({ videoGenEvents } = await import('./events.js'));
+
+ // No output file was ever written (stalled before output), so even though
+ // the fs mock returns true, the failure path must not treat this as a
+ // watchdog success — that gate keys on completionWatchdogFired, not this.
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const hang = makeHangingProc();
+ vi.mocked(spawnDetached).mockImplementationOnce(async () => hang.proc);
+
+ const events = [];
+ const onCompleted = (e) => events.push(['completed', e]);
+ const onFailed = (e) => events.push(['failed', e]);
+ videoGenEvents.on('completed', onCompleted);
+ videoGenEvents.on('failed', onFailed);
+
+ generateVideo({
+ jobId: 'idle-stall-fails-job',
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx2_unified',
+ prompt: 'stall then fail',
+ width: 512, height: 512, numFrames: 25, fps: 24,
+ mode: 'text',
+ });
+ await vi.advanceTimersByTimeAsync(0);
+
+ // Deadline elapses with no output → SIGKILL.
+ await vi.advanceTimersByTimeAsync(60001);
+ expect(hang.proc.kill).toHaveBeenCalledWith('SIGKILL');
+ // The OS delivers the kill → 'close' fires with signal SIGKILL.
+ hang.fireClose(null, 'SIGKILL');
+ await vi.advanceTimersByTimeAsync(0);
+
+ videoGenEvents.off('completed', onCompleted);
+ videoGenEvents.off('failed', onFailed);
+
+ const failed = events.find(([k]) => k === 'failed');
+ expect(failed).toBeTruthy();
+ expect(events.map(([k]) => k)).not.toContain('completed');
+ expect(failed[1].error).toMatch(/stalled/i);
+ expect(failed[1].error).toMatch(/VIDEOGEN_IDLE_STALL_MS/);
+ });
+
+ it('does NOT fire the idle timer when the child exits cleanly (timer cleared on close)', async () => {
+ process.env.VIDEOGEN_IDLE_STALL_MS = '60000';
+ vi.resetModules();
+ ({ generateVideo } = await import('./local.js'));
+
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const hang = makeHangingProc();
+ vi.mocked(spawnDetached).mockImplementationOnce(async () => hang.proc);
+
+ generateVideo({
+ jobId: 'idle-stall-clean-exit',
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx2_unified',
+ prompt: 'render and exit',
+ width: 512, height: 512, numFrames: 25, fps: 24,
+ mode: 'text',
+ });
+ await vi.advanceTimersByTimeAsync(0);
+
+ // Child emits its result and exits cleanly well within the window.
+ hang.emitStdout('{"video_path": "/data/videos/out.mp4"}\n');
+ hang.proc.exitCode = 0;
+ hang.fireClose(0, null);
+ await vi.advanceTimersByTimeAsync(0);
+
+ // Advancing past the idle window must NOT trigger a SIGKILL — close cleared it.
+ await vi.advanceTimersByTimeAsync(120000);
+ expect(hang.proc.kill).not.toHaveBeenCalled();
+ });
+
+ it('falls back to the default window on a missing/invalid VIDEOGEN_IDLE_STALL_MS', async () => {
+ // Invalid values must not collapse the guard to 0/NaN (which would kill
+ // every render instantly) — they fall back to the generous default.
+ for (const bad of ['', '0', '-5', 'lots']) {
+ // eslint-disable-next-line no-await-in-loop
+ await (async () => {
+ if (bad === '') delete process.env.VIDEOGEN_IDLE_STALL_MS;
+ else process.env.VIDEOGEN_IDLE_STALL_MS = bad;
+ vi.resetModules();
+ ({ generateVideo } = await import('./local.js'));
+
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const hang = makeHangingProc();
+ vi.mocked(spawnDetached).mockImplementationOnce(async () => hang.proc);
+
+ generateVideo({
+ jobId: `idle-stall-default-${bad || 'unset'}`,
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx2_unified',
+ prompt: 'default window',
+ width: 512, height: 512, numFrames: 25, fps: 24,
+ mode: 'text',
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ // A minute in — far past 0/NaN but well short of the 10-min default —
+ // the render must still be alive.
+ await vi.advanceTimersByTimeAsync(60000);
+ expect(hang.proc.kill).not.toHaveBeenCalled();
+ })();
+ }
+ delete process.env.VIDEOGEN_IDLE_STALL_MS;
+ });
+});
+
describe('generateVideo — video LoRA (--user-loras) arg threading', () => {
it('emits --user-loras JSON with resolved path + strength for ltx2 renders', async () => {
const { spawnDetached } = await import('../../lib/detachedSpawn.js');