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

retry an LTX-2 render once when the Metal watchdog aborts the Gemma prompt encoder (#4589)

[._.]/ Adam Eivyd7256de2196a
diff --git a/scripts/generate_ltx2.py b/scripts/generate_ltx2.py
index 6caaf8daab..cdb62481f7 100644
--- a/scripts/generate_ltx2.py
+++ b/scripts/generate_ltx2.py
@@ -56,6 +56,7 @@ Exit strategy — os._exit(0) in main():
from __future__ import annotations
import argparse
+import functools
import importlib
import inspect
import json
@@ -361,6 +362,75 @@ def configure_negative_prompt(negative_prompt: str) -> None:
emit_status("Using custom negative prompt")
+# Boundary markers bracketing the Gemma prompt encode. PortOS reads these off
+# stderr (generateVideoHelpers.js) to tell a render that died INSIDE the encoder
+# from one that died in the denoise loop — only the former is worth relaunching
+# with a smaller prompt budget. Kept as module constants so the shape is
+# assertable from the test suite rather than duplicated as literals.
+PROMPT_ENCODE_BEGIN_MARKER = "STAGE:encode-prompt"
+PROMPT_ENCODE_END_MARKER = "STAGE:encode-prompt-done"
+
+
+def configure_gemma_max_length(max_length: int | None) -> None:
+ """Pin the Gemma prompt-encode sequence length for this run.
+
+ ltx-2-mlx reads ``LTX2_GEMMA_MAX_LENGTH`` at encode time
+ (``ltx_pipelines_mlx.utils.blocks.PromptEncoder.encode``, and again in
+ ``_base`` for Prompt Relay token ranges), defaulting to 1024. PortOS passes a
+ lowered value on its one-shot relaunch after the macOS Metal command-buffer
+ watchdog aborts the encoder, so this ASSIGNS rather than ``setdefault``s: an
+ explicit flag has to beat whatever the parent environment already carried.
+
+ No-op when the flag is absent, which leaves upstream's own default in force.
+ """
+ if max_length is None:
+ return
+ if max_length < 1:
+ raise SystemExit(f"--gemma-max-length must be a positive integer; got {max_length}.")
+ os.environ["LTX2_GEMMA_MAX_LENGTH"] = str(max_length)
+ emit_status(f"Gemma prompt-encode capped at {max_length} tokens")
+
+
+def install_prompt_encode_markers() -> None:
+ """Bracket every Gemma prompt encode with the two STAGE: markers.
+
+ ``PromptEncoder.encode`` is the single chokepoint every mode's prompt
+ conditioning routes through (``__call__`` fans out to it for both the single
+ and batched shapes), so patching it on the CLASS covers text/image/fflf/
+ extend/a2v/ic without touching a runner. Same shape as
+ ``install_ltx25_encoder_override`` above, and idempotent via the marker
+ attribute so a double install can't nest the brackets.
+
+ The end marker means "control left the encoder", not "the encode succeeded":
+ it is emitted from ``finally``, so a Python-level encode failure also clears
+ the phase. That biases PortOS AWAY from relaunching, which is the safe
+ direction — a hard Metal abort kills the process outright, so ``finally``
+ never runs and the phase correctly stays open.
+
+ Silently skipped on a pin that does not expose ``PromptEncoder``; PortOS then
+ simply never sees an encode phase and never arms the retry.
+ """
+ try:
+ from ltx_pipelines_mlx.utils.blocks import PromptEncoder
+ except ImportError:
+ return
+
+ original = getattr(PromptEncoder, "encode", None)
+ if original is None or getattr(original, "_portos_prompt_encode_markers", False):
+ return
+
+ @functools.wraps(original)
+ def encode(self, *args, **kwargs):
+ print(PROMPT_ENCODE_BEGIN_MARKER, file=sys.stderr, flush=True)
+ try:
+ return original(self, *args, **kwargs)
+ finally:
+ print(PROMPT_ENCODE_END_MARKER, file=sys.stderr, flush=True)
+
+ encode._portos_prompt_encode_markers = True
+ PromptEncoder.encode = encode
+
+
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description="PortOS ltx-2-mlx bridge")
p.add_argument("--mode", required=True, choices=["text", "image", "fflf", "extend", "a2v", "ic"])
@@ -469,6 +539,12 @@ def parse_args() -> argparse.Namespace:
help="rel_l1_thresh for TeaCache on extend/a2v Stage 1. Higher = more "
"skipping = faster but lower fidelity (~1.2x at 0.5, up to ~3x at 1.5). "
"Omit to use the pipeline default (0.5).")
+ p.add_argument("--gemma-max-length", type=int, default=None,
+ help="Gemma prompt-encode sequence length (LTX2_GEMMA_MAX_LENGTH; "
+ "upstream default 1024). PortOS lowers this on its one-shot "
+ "relaunch after the macOS Metal command-buffer watchdog aborts "
+ "the prompt encoder. An explicit value always wins over the "
+ "ambient environment.")
return p.parse_args()
@@ -1236,6 +1312,8 @@ def main() -> NoReturn:
# before any model load). Each run_* sets pipe._pending_loras from this.
args.user_lora_specs = parse_user_loras(args.user_loras)
configure_negative_prompt(args.negative_prompt)
+ configure_gemma_max_length(args.gemma_max_length)
+ install_prompt_encode_markers()
runners = {
"text": run_text,
diff --git a/scripts/generate_ltx2.test.js b/scripts/generate_ltx2.test.js
index 4dc0622c39..715868c34f 100644
--- a/scripts/generate_ltx2.test.js
+++ b/scripts/generate_ltx2.test.js
@@ -341,4 +341,131 @@ describe.skipIf(!pyBin)('generate_ltx2.py', () => {
expect(output).toMatch(/needs an LTX-2\.5 pack whose own conditioner is gemma4/);
expect(output).toMatch(/GemmaLanguageModel/);
});
+
+ // ── Gemma prompt-encode budget + boundary markers (#4589) ──────────────────
+ // The markers are what lets PortOS tell "the Metal watchdog killed the prompt
+ // encoder" (worth one relaunch at a smaller budget) from "it killed the
+ // denoise loop" (not worth anything), so their exact text and their emission
+ // on BOTH the success and the failure path are load-bearing.
+ const stubPromptEncoderModule = (body) => [
+ 'import sys, types',
+ 'pkg = types.ModuleType("ltx_pipelines_mlx")',
+ 'utils = types.ModuleType("ltx_pipelines_mlx.utils")',
+ 'blocks = types.ModuleType("ltx_pipelines_mlx.utils.blocks")',
+ 'class PromptEncoder:',
+ ...body,
+ 'blocks.PromptEncoder = PromptEncoder',
+ 'sys.modules["ltx_pipelines_mlx"] = pkg',
+ 'sys.modules["ltx_pipelines_mlx.utils"] = utils',
+ 'sys.modules["ltx_pipelines_mlx.utils.blocks"] = blocks',
+ ];
+
+ it('brackets a successful prompt encode with the two markers, once per install', () => {
+ const output = runPython(`${importRunner}\n${[
+ ...stubPromptEncoderModule([
+ ' def encode(self, prompt):',
+ ' print("ENCODED:" + prompt)',
+ ' return ("video", "audio")',
+ ]),
+ 'import contextlib',
+ // Installed twice on purpose: main() runs once, but an idempotent patch is
+ // what keeps a future second install from nesting the brackets and
+ // emitting the begin marker twice for one encode.
+ 'runner.install_prompt_encode_markers()',
+ 'runner.install_prompt_encode_markers()',
+ 'with contextlib.redirect_stderr(sys.stdout):',
+ ' result = PromptEncoder().encode("a cat")',
+ 'print(result)',
+ ].join('\n')}`);
+ const lines = output.trim().split(/\r?\n/);
+ expect(lines).toEqual([
+ 'STAGE:encode-prompt',
+ 'ENCODED:a cat',
+ 'STAGE:encode-prompt-done',
+ "('video', 'audio')",
+ ]);
+ });
+
+ // The end marker means "control left the encoder", not "the encode succeeded".
+ // Emitting it from `finally` biases PortOS AWAY from relaunching, which is the
+ // safe direction — a hard Metal abort kills the process outright, so `finally`
+ // never runs and the phase correctly stays open.
+ it('still emits the end marker when the encode raises', () => {
+ const output = runPython(`${importRunner}\n${[
+ ...stubPromptEncoderModule([
+ ' def encode(self, prompt):',
+ ' raise RuntimeError("gemma exploded")',
+ ]),
+ 'import contextlib',
+ 'runner.install_prompt_encode_markers()',
+ 'with contextlib.redirect_stderr(sys.stdout):',
+ ' try:',
+ ' PromptEncoder().encode("a cat")',
+ ' except RuntimeError as exc:',
+ ' print("RAISED:" + str(exc))',
+ ].join('\n')}`);
+ expect(output.trim().split(/\r?\n/)).toEqual([
+ 'STAGE:encode-prompt',
+ 'STAGE:encode-prompt-done',
+ 'RAISED:gemma exploded',
+ ]);
+ });
+
+ // A pin without PromptEncoder must not crash the render — PortOS simply never
+ // sees an encode phase there, and so never arms the retry.
+ it('is a no-op when the pin exposes no PromptEncoder', () => {
+ const output = runPython(`${importRunner}\n${[
+ 'import sys',
+ 'sys.modules.pop("ltx_pipelines_mlx.utils.blocks", None)',
+ 'runner.install_prompt_encode_markers()',
+ 'print("ok")',
+ ].join('\n')}`);
+ expect(output.trim()).toBe('ok');
+ });
+
+ // ltx-2-mlx reads LTX2_GEMMA_MAX_LENGTH at encode time and defaults it to
+ // 1024, so the flag has to ASSIGN — a setdefault would be swallowed by the
+ // ambient value the parent already exported and the relaunch would re-run at
+ // the budget that just aborted.
+ it.each([
+ ['None', 'None', null, '1024'],
+ ['a lowered budget', '512', null, '512'],
+ ['a lowered budget over an ambient value', '512', '1024', '512'],
+ ])('configure_gemma_max_length(%s) resolves LTX2_GEMMA_MAX_LENGTH to the expected value', (_label, flag, ambient, expected) => {
+ const output = runPython(`${importRunner}\n${[
+ 'import os',
+ ambient === null
+ ? 'os.environ.pop("LTX2_GEMMA_MAX_LENGTH", None)'
+ : `os.environ["LTX2_GEMMA_MAX_LENGTH"] = ${JSON.stringify(ambient)}`,
+ `runner.configure_gemma_max_length(${flag})`,
+ // Read back through the same default upstream applies, so "unset" and
+ // "explicitly 1024" are both expressed as the value the encoder would use.
+ 'print(os.environ.get("LTX2_GEMMA_MAX_LENGTH", "1024"))',
+ ].join('\n')}`);
+ expect(output.trim()).toBe(expected);
+ });
+
+ it.each([['0'], ['-1']])('rejects a non-positive --gemma-max-length (%s)', (value) => {
+ const output = runPython(`${importRunner}\n${[
+ 'try:',
+ ` runner.configure_gemma_max_length(${value})`,
+ 'except SystemExit as exc:',
+ ' print(str(exc))',
+ 'else:',
+ ' raise SystemExit("a non-positive gemma budget was accepted")',
+ ].join('\n')}`);
+ expect(output).toMatch(/must be a positive integer/);
+ });
+
+ it.each([
+ ['omitted', [], 'None'],
+ ['given', ['--gemma-max-length', '512'], '512'],
+ ])('parses --gemma-max-length when %s', (_label, extra, expected) => {
+ const output = runPython(`${importRunner}\n${[
+ 'import sys',
+ `sys.argv = ["generate_ltx2.py", "--mode", "text", "--prompt", "p", "--output", "/tmp/o.mp4", "--model", "m"] + ${JSON.stringify(extra)}`,
+ 'print(runner.parse_args().gemma_max_length)',
+ ].join('\n')}`);
+ expect(output.trim()).toBe(expected);
+ });
});
diff --git a/server/services/videoGen/generateVideoHelpers.js b/server/services/videoGen/generateVideoHelpers.js
index bc5553d832..1e8c2ad14d 100644
--- a/server/services/videoGen/generateVideoHelpers.js
+++ b/server/services/videoGen/generateVideoHelpers.js
@@ -79,6 +79,15 @@ export function formatDownloadMessage(rawText, byteInfo) {
return `Downloading model... ${rawText}`;
}
+/**
+ * Boundary markers `scripts/generate_ltx2.py` prints on stderr around the Gemma
+ * prompt encode (`install_prompt_encode_markers`). Matched EXACTLY, never by
+ * prefix — `STAGE:encode-prompt-done` starts with `STAGE:encode-prompt`, so a
+ * `startsWith` test would read the end of the encode as its beginning.
+ */
+export const PROMPT_ENCODE_BEGIN_MARKER = 'STAGE:encode-prompt';
+export const PROMPT_ENCODE_END_MARKER = 'STAGE:encode-prompt-done';
+
/**
* Build the stdout/stderr line handler for one generation. Parses the
* python child's STATUS:/STAGE:/DOWNLOAD:/tqdm protocol into SSE frames
@@ -139,6 +148,14 @@ export function makeVideoGenLineHandler({ job, jobId, pythonNoiseRe }) {
return true;
}
if (line.startsWith('STAGE:')) {
+ // Gemma prompt-encode boundary (scripts/generate_ltx2.py). Stamped on the
+ // job as a three-state phase — absent = this runner never reports one,
+ // 'active' = encoding right now, 'done' = finished — so a later SIGABRT can
+ // be attributed to the encode without conflating "never reported" with
+ // "finished". Compared exactly: the '-done' marker is a prefix extension of
+ // the begin marker. See planPromptEncodingRetry.
+ if (line === PROMPT_ENCODE_BEGIN_MARKER) job.promptEncodePhase = 'active';
+ else if (line === PROMPT_ENCODE_END_MARKER) job.promptEncodePhase = 'done';
const parts = line.split(':');
// Track phase for tqdm bar formatting — STAGE:download* sets download mode,
// other phases (inference, encode, decode, etc.) clear it.
@@ -338,6 +355,95 @@ export function describeSignalDeath(signal, { fingerprint = null } = {}) {
return fp ? `${cause} [runtime: ${fp}]` : cause;
}
+/**
+ * Gemma prompt-encode sequence length. `LTX2_GEMMA_MAX_LENGTH` is read by
+ * ltx-2-mlx at encode time (`utils/blocks.py#PromptEncoder.encode`) and defaults
+ * to 1024 there; the retry halves it so the encoder's attention matrices are a
+ * quarter the size and each Metal command buffer finishes well inside the
+ * watchdog window. Halving (rather than a deeper cut) keeps a long prompt's
+ * tail intact — the tokenizer truncates from the LEFT, so a smaller budget
+ * silently drops the START of the prompt, which is where the subject usually
+ * is.
+ */
+export const DEFAULT_GEMMA_MAX_LENGTH = 1024;
+export const RETRY_GEMMA_MAX_LENGTH = 512;
+
+// The macOS Metal command-buffer watchdog reports WHY it killed a buffer via a
+// `kIOGPUCommandBufferCallbackError*` enum name in the abort text. Two of those
+// mean "this buffer ran too long for the compositor to stay responsive", which
+// is the failure a smaller prompt-encode buffer actually fixes:
+// - ...ErrorTimeout — the classic signature
+// - ...ErrorImpactingInteractivity — what newer Apple silicon / macOS report
+// instead, and the reason a Timeout-only match never armed the retry there.
+// MLX also surfaces the timeout case in prose ("Caused GPU Timeout Error"), so
+// that phrasing is accepted too.
+const METAL_WATCHDOG_RE = /kIOGPUCommandBufferCallbackError(?:Timeout|ImpactingInteractivity)|Caused GPU Timeout Error/i;
+// ...and two that must NOT arm it. An out-of-memory abort is not a watchdog
+// timeout — a shorter prompt does not fix it, and retrying burns another model
+// load on a machine that is already out of headroom. An innocent victim was
+// killed because SOME OTHER process wedged the GPU, so this render's prompt
+// length is irrelevant. Either name anywhere in the captured text vetoes the
+// retry, even alongside a timeout: a mixed abort is exactly the case where the
+// timeout is a downstream symptom rather than the cause.
+const METAL_WATCHDOG_VETO_RE = /kIOGPUCommandBufferCallbackError(?:OutOfMemory|InnocentVictim)/i;
+
+/**
+ * Whether a render child died to the macOS Metal command-buffer watchdog WHILE
+ * the Gemma prompt encoder was running. Pure.
+ *
+ * `promptEncodePhase` is a three-state sentinel, and all three states are
+ * distinct on purpose:
+ * - `null` — the runner never reported an encode boundary. Every runtime
+ * other than the LTX-2 MLX helper is permanently here, so an
+ * unreported phase can never be mistaken for a live encode.
+ * - `'active'` — the encode began and never finished. The ONLY qualifying
+ * state: the child died mid-encode, before any denoise step.
+ * - `'done'` — the encode finished. Anything that aborts after this is a
+ * denoise/decode failure that a shorter prompt cannot fix.
+ *
+ * @param {object} [opts]
+ * @param {string|null} [opts.signal] - signal name from `proc.on('close')`
+ * @param {string} [opts.stderr] - captured stderr tail from the dead child
+ * @param {'active'|'done'|null} [opts.promptEncodePhase]
+ * @returns {boolean}
+ */
+export function isPromptEncodingMetalWatchdog({ signal = null, stderr = '', promptEncodePhase = null } = {}) {
+ // The Metal layer raises a C++ exception that terminate() turns into SIGABRT;
+ // a watchdog kill never arrives as a clean non-zero exit.
+ if (signal !== 'SIGABRT') return false;
+ if (promptEncodePhase !== 'active') return false;
+ const text = typeof stderr === 'string' ? stderr : '';
+ if (METAL_WATCHDOG_VETO_RE.test(text)) return false;
+ return METAL_WATCHDOG_RE.test(text);
+}
+
+/**
+ * Decide whether one render may be relaunched after a prompt-encode watchdog
+ * abort, and with what Gemma budget. Pure — returns the plan, never acts.
+ *
+ * Returns `null` for "do not retry" and `{ gemmaMaxLength }` for "relaunch this
+ * same job once with that budget". Exactly one retry is ever allowed: a second
+ * watchdog abort at the reduced budget is a real failure the user must see, not
+ * something to keep grinding the GPU over.
+ *
+ * @param {object} [opts]
+ * @param {string|null} [opts.signal]
+ * @param {string} [opts.stderr]
+ * @param {'active'|'done'|null} [opts.promptEncodePhase]
+ * @param {number} [opts.retriesUsed] - retries already spent on this job
+ * @param {string} [opts.platform] - `process.platform` of the host
+ * @returns {{ gemmaMaxLength: number }|null}
+ */
+export function planPromptEncodingRetry({ signal = null, stderr = '', promptEncodePhase = null, retriesUsed = 0, platform = process.platform } = {}) {
+ // The command-buffer watchdog is a macOS construct. A Windows/CUDA render
+ // that somehow produced a matching string must not be relaunched with an
+ // Apple-specific mitigation.
+ if (platform !== 'darwin') return null;
+ if (!Number.isInteger(retriesUsed) || retriesUsed > 0) return null;
+ if (!isPromptEncodingMetalWatchdog({ signal, stderr, promptEncodePhase })) return null;
+ return { gemmaMaxLength: RETRY_GEMMA_MAX_LENGTH };
+}
+
/**
* Whether a PortOS-fired SIGKILL should be treated as success rather than a
* failure. Two Node-side watchdogs can SIGKILL a render:
diff --git a/server/services/videoGen/generateVideoHelpers.test.js b/server/services/videoGen/generateVideoHelpers.test.js
index 7d1f1f6506..66e9e67d3d 100644
--- a/server/services/videoGen/generateVideoHelpers.test.js
+++ b/server/services/videoGen/generateVideoHelpers.test.js
@@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
import { writeFileSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
-import { makeVideoGenLineHandler, isWatchdogSuccess, finalizeGeneratedVideo, parseByteProgress, formatBytes, formatDownloadMessage, describeSignalDeath, formatRuntimeFingerprint, describeRenderConditioning, RENDER_INPUTS_VERSION } from './generateVideoHelpers.js';
+import { makeVideoGenLineHandler, isWatchdogSuccess, finalizeGeneratedVideo, parseByteProgress, formatBytes, formatDownloadMessage, describeSignalDeath, formatRuntimeFingerprint, describeRenderConditioning, isPromptEncodingMetalWatchdog, planPromptEncodingRetry, DEFAULT_GEMMA_MAX_LENGTH, RETRY_GEMMA_MAX_LENGTH, RENDER_INPUTS_VERSION } from './generateVideoHelpers.js';
describe('parseByteProgress', () => {
it('parses single byte value (e.g., "2.5G")', () => {
@@ -120,6 +120,30 @@ describe('makeVideoGenLineHandler', () => {
const sseFrames = () => sse.mock.calls.map((c) => c[1]);
const eventsOfType = (t) => emitted.filter((e) => e.type === t).map((e) => e.payload);
+ // Prompt-encode phase (#4589) — the signal that decides whether a later
+ // SIGABRT is worth one relaunch at a smaller Gemma budget.
+ it('tracks the Gemma prompt-encode phase as three distinct states', () => {
+ // Never reported: every runtime other than the LTX-2 MLX helper stays here,
+ // and an unstamped field must not read as "encoding right now".
+ expect(job.promptEncodePhase).toBeUndefined();
+ handle('STAGE:load-pipeline');
+ expect(job.promptEncodePhase).toBeUndefined();
+
+ handle('STAGE:encode-prompt');
+ expect(job.promptEncodePhase).toBe('active');
+
+ // The end marker is a PREFIX EXTENSION of the begin marker, so a startsWith
+ // comparison would read the end of the encode as another beginning and leave
+ // the phase open forever.
+ handle('STAGE:encode-prompt-done');
+ expect(job.promptEncodePhase).toBe('done');
+ });
+
+ it('still surfaces the prompt-encode markers to the client as status frames', () => {
+ handle('STAGE:encode-prompt');
+ expect(eventsOfType('status')).toContainEqual({ generationId: 'job-12345678', message: 'encode-prompt' });
+ });
+
it('repeats the job ETA on every progress frame, and omits it when absent (#3801)', () => {
// No estimate on the job → the key must be absent, never etaMs: 0.
handle('STAGE:inference:step:5:30:Rendering');
@@ -446,3 +470,104 @@ describe('isWatchdogSuccess', () => {
}
});
});
+
+// ── Gemma prompt-encode watchdog retry (#4589) ──────────────────────────────
+// A real Metal abort cannot be reproduced in a unit test, so the coverage here
+// is over the two decisions PortOS actually makes from the wreckage: which
+// abort text counts as a prompt-encode watchdog kill, and whether the render
+// may be relaunched.
+describe('isPromptEncodingMetalWatchdog', () => {
+ // The abort banner MLX prints on the way down, in the two shapes the watchdog
+ // uses. The impacting-interactivity one is what newer Apple silicon / macOS
+ // report where older combinations reported a timeout — matching only the
+ // timeout wording is exactly the portability bug this classifier fixes.
+ const TIMEOUT_ABORT = 'libc++abi: terminating due to uncaught exception of type std::runtime_error: [METAL] Command buffer execution failed: Caused GPU Timeout Error (00000002:kIOGPUCommandBufferCallbackErrorTimeout)';
+ const INTERACTIVITY_ABORT = 'libc++abi: terminating due to uncaught exception of type std::runtime_error: [METAL] Command buffer execution failed: (00000004:kIOGPUCommandBufferCallbackErrorImpactingInteractivity)';
+ const OOM_ABORT = '[METAL] Command buffer execution failed: (00000008:kIOGPUCommandBufferCallbackErrorOutOfMemory)';
+ const VICTIM_ABORT = '[METAL] Command buffer execution failed: (00000006:kIOGPUCommandBufferCallbackErrorInnocentVictim)';
+
+ it.each([
+ ['the classic timeout signature', TIMEOUT_ABORT],
+ ['the impacting-interactivity signature newer macOS reports instead', INTERACTIVITY_ABORT],
+ ])('recognizes %s', (_label, stderr) => {
+ expect(isPromptEncodingMetalWatchdog({ signal: 'SIGABRT', stderr, promptEncodePhase: 'active' })).toBe(true);
+ });
+
+ // Neither is a "this buffer ran too long" kill, so neither is fixed by a
+ // shorter prompt: OOM means the machine is out of headroom, and an innocent
+ // victim was killed for some OTHER process wedging the GPU.
+ it.each([
+ ['an out-of-memory abort', OOM_ABORT],
+ ['an innocent-victim abort', VICTIM_ABORT],
+ ])('excludes %s', (_label, stderr) => {
+ expect(isPromptEncodingMetalWatchdog({ signal: 'SIGABRT', stderr, promptEncodePhase: 'active' })).toBe(false);
+ });
+
+ // A mixed abort is the case where the timeout is a downstream symptom of the
+ // real cause, so the veto wins rather than the match.
+ it('excludes an abort that carries both a timeout and an out-of-memory cause', () => {
+ expect(isPromptEncodingMetalWatchdog({
+ signal: 'SIGABRT',
+ stderr: `${TIMEOUT_ABORT}\n${OOM_ABORT}`,
+ promptEncodePhase: 'active',
+ })).toBe(false);
+ });
+
+ // The three phase states must stay distinct: "never reported" is every
+ // non-LTX-2 runtime and must never read as "encoding right now".
+ it.each([
+ ['done — the abort landed in the denoise loop, which a shorter prompt cannot fix', 'done'],
+ ['null — this runner never reported an encode boundary at all', null],
+ ['undefined — same, expressed as an unstamped job field', undefined],
+ ])('refuses to fire when the prompt-encode phase is %s', (_label, promptEncodePhase) => {
+ expect(isPromptEncodingMetalWatchdog({ signal: 'SIGABRT', stderr: TIMEOUT_ABORT, promptEncodePhase })).toBe(false);
+ });
+
+ // A watchdog kill always arrives as SIGABRT (the Metal layer raises a C++
+ // exception that terminate() converts), never as a clean non-zero exit or an
+ // OOM SIGKILL.
+ it.each([[null], ['SIGKILL'], ['SIGTERM'], ['SIGSEGV']])('refuses to fire on signal %s', (signal) => {
+ expect(isPromptEncodingMetalWatchdog({ signal, stderr: TIMEOUT_ABORT, promptEncodePhase: 'active' })).toBe(false);
+ });
+
+ it('tolerates a missing/blank stderr tail and an empty call', () => {
+ expect(isPromptEncodingMetalWatchdog()).toBe(false);
+ expect(isPromptEncodingMetalWatchdog({ signal: 'SIGABRT', promptEncodePhase: 'active' })).toBe(false);
+ expect(isPromptEncodingMetalWatchdog({ signal: 'SIGABRT', stderr: null, promptEncodePhase: 'active' })).toBe(false);
+ });
+});
+
+describe('planPromptEncodingRetry', () => {
+ const WATCHDOG_ABORT = '[METAL] Command buffer execution failed: (00000004:kIOGPUCommandBufferCallbackErrorImpactingInteractivity)';
+ const qualifying = {
+ signal: 'SIGABRT',
+ stderr: WATCHDOG_ABORT,
+ promptEncodePhase: 'active',
+ retriesUsed: 0,
+ platform: 'darwin',
+ };
+
+ it('plans one relaunch at the reduced Gemma budget', () => {
+ expect(planPromptEncodingRetry(qualifying)).toEqual({ gemmaMaxLength: RETRY_GEMMA_MAX_LENGTH });
+ // The reduced budget is a real cut from what upstream would otherwise use —
+ // a plan that handed back the default would relaunch into the same abort.
+ expect(RETRY_GEMMA_MAX_LENGTH).toBeLessThan(DEFAULT_GEMMA_MAX_LENGTH);
+ });
+
+ it('allows exactly one — a second abort at the reduced budget is a real failure', () => {
+ expect(planPromptEncodingRetry({ ...qualifying, retriesUsed: 1 })).toBeNull();
+ expect(planPromptEncodingRetry({ ...qualifying, retriesUsed: 2 })).toBeNull();
+ });
+
+ // The command-buffer watchdog is a macOS construct; a Windows/CUDA render that
+ // somehow produced a matching string must not be relaunched with an
+ // Apple-specific mitigation.
+ it.each([['win32'], ['linux']])('never fires on %s', (platform) => {
+ expect(planPromptEncodingRetry({ ...qualifying, platform })).toBeNull();
+ });
+
+ it('passes the classifier verdict straight through', () => {
+ expect(planPromptEncodingRetry({ ...qualifying, promptEncodePhase: 'done' })).toBeNull();
+ expect(planPromptEncodingRetry({ ...qualifying, signal: 'SIGKILL' })).toBeNull();
+ });
+});
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index 1d0be03014..70c5ddcf55 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -40,7 +40,7 @@ import {
import { hfChildEnv } from '../../lib/hfToken.js';
import { inspectModelCache, findCachedRepoFile, findCachedRepoFiles } from '../../lib/hfCache.js';
import { safeChildProcessEnv, safeChildProcessOptions } from '../../lib/processEnv.js';
-import { makeVideoGenLineHandler, finalizeGeneratedVideo, isWatchdogSuccess, describeSignalDeath, describeRenderConditioning, RENDER_INPUTS_VERSION } from './generateVideoHelpers.js';
+import { makeVideoGenLineHandler, finalizeGeneratedVideo, isWatchdogSuccess, describeSignalDeath, describeRenderConditioning, planPromptEncodingRetry, RENDER_INPUTS_VERSION } from './generateVideoHelpers.js';
import { assertSafeLoraFilename, getLoraKeyLayout } from '../loras.js';
import { videoLoraFamily, isLtx2FamilyRuntime } from '../../lib/runners.js';
import {
@@ -116,6 +116,12 @@ const AV_LORA_HELPER_SCRIPT = join(PATHS.root, 'scripts', 'generate_av_lora.py')
const execFileAsync = promisify(execFile);
const MODULE_NOT_FOUND_RE = /ModuleNotFoundError: No module named ['"]([^'"]+)['"]/;
+// How many stderr lines of a render child are kept for post-mortem
+// classification (see planPromptEncodingRetry). A Metal abort prints its banner
+// as the last thing before the process dies, so a short tail always carries it,
+// while the bound keeps a chatty runtime from growing the buffer for the whole
+// render.
+const STDERR_TAIL_LINES = 40;
// Shared-gallery uploads use the upload filename stem as their history id.
// Rendered clips retain their UUID ids, so service callers may act on either
// form after route validation.
@@ -208,6 +214,12 @@ export const defaultVideoModelId = () => getDefaultVideoModelId();
const jobs = new Map();
let activeProcess = null;
+// Bumped on every cancel() call. A render relaunch (the prompt-encode retry in
+// generateVideo) clears activeProcess before it awaits the replacement spawn, so
+// for that one window cancel() has nothing to kill and returns false. Comparing
+// this counter across the await is what lets the relaunch notice the cancel it
+// could not otherwise see, and abandon the replacement child.
+let cancelEpoch = 0;
// Chain state for multi-chunk renders. cancel() flips `stopped` so the chain
// loop bails before kicking off the next chunk; the in-flight chunk's child
// is killed via the existing activeProcess SIGTERM path. There is at most
@@ -217,6 +229,7 @@ let activeChain = null;
export const attachSseClient = (jobId, res) => attachSse(jobs, jobId, res);
export const cancel = () => {
+ cancelEpoch += 1;
// Flag the chain (if any) so the loop stops between chunks. We still
// kill the in-flight child below — without that the current chunk would
// run to completion before the chain saw the stop flag.
@@ -1571,8 +1584,17 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
}
const releaseHeavyClaim = () => heavyClaim.release()
.catch((err) => console.error(`❌ Video generation claim release [${jobId.slice(0, 8)}]: ${err.message}`));
- let proc;
+ // The first render child. Named apart from the `proc` each wireRenderChild()
+ // call binds, so a relaunch cannot be confused with the original.
+ let firstProc;
let claimHandedOff = false;
+ // Prompt-encode relaunches already spent on this job. Exactly one is allowed:
+ // a second watchdog abort at the reduced budget is a real failure the user has
+ // to see, not something to keep grinding the GPU over.
+ let promptEncodingRetriesUsed = 0;
+ // Hoisted out of the try so a relaunch can respawn with the SAME child env
+ // plus a lowered Gemma budget, instead of rebuilding it from scratch.
+ let childEnv;
try {
const memoryReport = await prepareLocalMemory();
if (memoryReport.unloaded.length) console.log(`🧹 Video generation [${jobId.slice(0, 8)}] freed ${memoryReport.unloaded.length} resident model(s)`);
@@ -1606,7 +1628,7 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// python helpers can authenticate snapshot_download() against gated repos
// (mirrors the imageGen child-spawn pattern). LTX-2 doesn't currently use
// a gated repo, but the merge is harmless when no token is configured.
- const childEnv = runtimeIsCacheOnly(model.runtime)
+ childEnv = runtimeIsCacheOnly(model.runtime)
? safeChildProcessEnv()
: await hfChildEnv();
delete childEnv.PYTHONPATH;
@@ -1633,283 +1655,455 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// still `proc.kill()` it directly by PID on cancel / watchdog. `cleanup: true`
// lets the helper drop that scratch dir on every terminal path (close/error)
// so it can't accumulate under data/videos.
- proc = await spawnDetached(bin, args, {
+ firstProc = await spawnDetached(bin, args, {
env: childEnv,
controlDir: join(PATHS.videos, '.detached', jobId),
cleanup: true,
killProcessGroup: runtimeNeedsProcessGroupKill(model.runtime),
});
- activeProcess = proc;
- await heavyClaim.handoffTo?.(proc.pid);
+ activeProcess = firstProc;
+ await heavyClaim.handoffTo?.(firstProc.pid);
claimHandedOff = true;
} catch (err) {
if (!claimHandedOff) await releaseHeavyClaim();
throw err;
}
- // Panel-side completion watchdog. Armed once we see the render's completion
- // marker on stdout; SIGKILLs the child if it hasn't exited after the grace
- // window. clearCompletionWatchdog() runs in every terminal path ('close',
- // 'error') so the timer can't outlive this child or fire against a recycled
- // PID. Armed at most once per child (re-seeing the marker is a no-op).
- let completionWatchdog = null;
- // Set when the watchdog itself fires the SIGKILL. The 'close' handler reads
- // it so it can treat that kill as success (the render already wrote its file —
- // we only killed a post-completion teardown hang) rather than reporting the
- // generic "killed, likely OOM" failure.
- let completionWatchdogFired = false;
- const clearCompletionWatchdog = () => {
- if (completionWatchdog) {
- clearTimeout(completionWatchdog);
- completionWatchdog = null;
- }
- };
- const armCompletionWatchdog = () => {
- if (completionWatchdog) return;
- completionWatchdog = setTimeout(() => {
- // Runs outside the Express request lifecycle — an uncaught throw here
- // would crash the Node process, so guard the whole body.
- try {
+ // ── one render child, fully wired ──────────────────────────────────────────
+ // Everything per-CHILD lives in here — the process handle, both watchdogs, the
+ // line readers, the close handler — so the same job can be relaunched once
+ // without minting a new one. Everything job-level (jobId, args, seed, meta,
+ // history entry, heavy claim, staged temp files) is closed over and survives
+ // the relaunch. The only thing that relaunches a render is a Metal
+ // command-buffer watchdog abort inside the Gemma prompt encoder; see
+ // maybeRelaunchForPromptEncoding below.
+ const wireRenderChild = (proc) => {
+ // The prompt-encode phase belongs to ONE child, but `job` outlives the
+ // relaunch — reset it explicitly so a phase left open by the child that just
+ // died can never be read as the replacement child's state.
+ job.promptEncodePhase = null;
+ // Panel-side completion watchdog. Armed once we see the render's completion
+ // marker on stdout; SIGKILLs the child if it hasn't exited after the grace
+ // window. clearCompletionWatchdog() runs in every terminal path ('close',
+ // 'error') so the timer can't outlive this child or fire against a recycled
+ // PID. Armed at most once per child (re-seeing the marker is a no-op).
+ let completionWatchdog = null;
+ // Set when the watchdog itself fires the SIGKILL. The 'close' handler reads
+ // it so it can treat that kill as success (the render already wrote its file —
+ // we only killed a post-completion teardown hang) rather than reporting the
+ // generic "killed, likely OOM" failure.
+ let completionWatchdogFired = false;
+ const clearCompletionWatchdog = () => {
+ if (completionWatchdog) {
+ clearTimeout(completionWatchdog);
completionWatchdog = null;
- // proc.killed covers a manual-cancel SIGTERM that hasn't reached close
- // yet (killWithEscalation sets it before exitCode/signalCode populate).
- if (activeProcess !== proc || proc.killed || proc.exitCode !== null || proc.signalCode !== null) return;
- console.log(`⚠️ video child reported completion but never exited — SIGKILL [${jobId.slice(0, 8)}]`);
- completionWatchdogFired = true;
- proc.kill('SIGKILL');
- } catch (err) {
- console.error(`❌ completion watchdog failed [${jobId.slice(0, 8)}]: ${err.message}`);
}
- }, COMPLETION_WATCHDOG_GRACE_MS);
- // Don't let the watchdog timer keep the event loop alive on its own.
- if (typeof completionWatchdog.unref === 'function') completionWatchdog.unref();
- };
+ };
+ const armCompletionWatchdog = () => {
+ if (completionWatchdog) return;
+ completionWatchdog = setTimeout(() => {
+ // Runs outside the Express request lifecycle — an uncaught throw here
+ // would crash the Node process, so guard the whole body.
+ try {
+ completionWatchdog = null;
+ // proc.killed covers a manual-cancel SIGTERM that hasn't reached close
+ // yet (killWithEscalation sets it before exitCode/signalCode populate).
+ if (activeProcess !== proc || proc.killed || proc.exitCode !== null || proc.signalCode !== null) return;
+ console.log(`⚠️ video child reported completion but never exited — SIGKILL [${jobId.slice(0, 8)}]`);
+ completionWatchdogFired = true;
+ proc.kill('SIGKILL');
+ } catch (err) {
+ console.error(`❌ completion watchdog failed [${jobId.slice(0, 8)}]: ${err.message}`);
+ }
+ }, COMPLETION_WATCHDOG_GRACE_MS);
+ // Don't let the watchdog timer keep the event loop alive on its own.
+ 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 {
+ // 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;
- // Also bail if the child is already being torn down by a manual
- // cancel: killWithEscalation() sends SIGTERM and sets `proc.killed`
- // BEFORE exitCode/signalCode populate on close. Without this check the
- // idle timer could still fire, set idleStallFired, and SIGKILL — and
- // the close handler would then finalize a user-canceled render (whose
- // partial .mp4 is on disk) as a SUCCESS instead of canceled/failed.
- if (activeProcess !== proc || proc.killed || 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();
+ };
+ const armIdleStallTimer = () => {
+ idleStallTimer = setTimeout(() => {
+ // Outside the Express request lifecycle — guard so an uncaught throw
+ // can't crash the Node process.
+ try {
+ idleStallTimer = null;
+ // Also bail if the child is already being torn down by a manual
+ // cancel: killWithEscalation() sends SIGTERM and sets `proc.killed`
+ // BEFORE exitCode/signalCode populate on close. Without this check the
+ // idle timer could still fire, set idleStallFired, and SIGKILL — and
+ // the close handler would then finalize a user-canceled render (whose
+ // partial .mp4 is on disk) as a SUCCESS instead of canceled/failed.
+ if (activeProcess !== proc || proc.killed || 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();
- };
- // 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
- // sleep — together they survive everything short of the user forcing sleep
- // from the Apple menu. `-w` makes caffeinate self-exit when our pid does, so
- // no manual cleanup is needed and a server crash mid-render still releases
- // the assertion. macOS-only — `caffeinate` is a darwin binary.
- if (process.platform === 'darwin' && proc.pid) {
- spawn('caffeinate', ['-dis', '-w', String(proc.pid)], { stdio: 'ignore', detached: false }).on('error', () => {});
- }
- // Without an 'error' handler, a missing/non-executable pythonPath would
- // 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}`);
- broadcastSse(job, { type: 'error', error: reason });
- videoGenEvents.emit('failed', { generationId: jobId, error: reason });
- activeProcess = null;
- void releaseHeavyClaim();
- // Spawn failed, so proc.on('close') will never fire — clean up every
- // temp file we own here, including the multipart upload, otherwise
- // ENOENT/permission errors leak files in os.tmpdir().
- // Defensive cleanup includes audio passed directly without the route's
- // uploadedTempPaths tracking. Duplicate unlinks remain harmless.
- void cleanupTempFiles({ includeUploads: true, includeUntrackedAudio: true });
- closeJobAfterDelay(jobs, jobId);
- });
- let missingPyModule = null;
-
- // The python child's STATUS:/STAGE:/DOWNLOAD:/tqdm → SSE-frame parser lives
- // in generateVideoHelpers.js so it can be unit-tested without a real child.
- // Returns true for a recognized progress/status/noise line (suppress raw
- // logging), false for an unhandled line worth raw-logging.
- const handleLine = makeVideoGenLineHandler({ job, jobId, pythonNoiseRe: PYTHON_NOISE_RE });
-
- // Per-stream line readers carry the partial trailing line across chunk
- // boundaries and decode through a StringDecoder, so a marker (or multibyte
- // char) split across a pipe chunk can't tear an event — and the final
- // unterminated line is emitted on 'close' via flush().
- const stdoutReader = createLineReader((raw) => {
- const line = raw.trim();
- if (!line) return;
- // mlx_video emits one JSON line on stdout when finished — capture it
- // for the result metadata; otherwise raw-log so we can debug failures.
- try {
- const parsed = JSON.parse(line);
- if (parsed.video_path) {
- job.resultJson = parsed;
- // The result JSON is the strongest "work is done" signal — arm the
- // watchdog so a post-completion teardown hang can't wedge the job.
- armCompletionWatchdog();
- }
- return;
- } catch { /* not JSON */ }
- // Some runtimes don't print the result JSON but do log the final
- // decode+mux line right before they should exit — treat it the same way.
- if (MUXING_DONE_RE.test(line)) armCompletionWatchdog();
- console.log(`🐍-out [${jobId.slice(0, 8)}] ${line}`);
- });
- const stderrReader = createLineReader((raw) => {
- // Record the root-cause module only — downstream imports in the same
- // traceback raise the same error against later names.
- if (!missingPyModule) {
- const m = raw.match(MODULE_NOT_FOUND_RE);
- if (m) missingPyModule = m[1];
+ // 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
+ // sleep — together they survive everything short of the user forcing sleep
+ // from the Apple menu. `-w` makes caffeinate self-exit when our pid does, so
+ // no manual cleanup is needed and a server crash mid-render still releases
+ // the assertion. macOS-only — `caffeinate` is a darwin binary.
+ if (process.platform === 'darwin' && proc.pid) {
+ spawn('caffeinate', ['-dis', '-w', String(proc.pid)], { stdio: 'ignore', detached: false }).on('error', () => {});
}
- if (!handleLine(raw)) console.log(`🐍 [${jobId.slice(0, 8)}] ${raw.trim()}`);
- }, { splitRe: /[\n\r]+/ });
-
- 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();
- stdoutReader.push(chunk);
- });
+ // Without an 'error' handler, a missing/non-executable pythonPath would
+ // 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}`);
+ broadcastSse(job, { type: 'error', error: reason });
+ videoGenEvents.emit('failed', { generationId: jobId, error: reason });
+ activeProcess = null;
+ void releaseHeavyClaim();
+ // Spawn failed, so proc.on('close') will never fire — clean up every
+ // temp file we own here, including the multipart upload, otherwise
+ // ENOENT/permission errors leak files in os.tmpdir().
+ // Defensive cleanup includes audio passed directly without the route's
+ // uploadedTempPaths tracking. Duplicate unlinks remain harmless.
+ void cleanupTempFiles({ includeUploads: true, includeUntrackedAudio: true });
+ closeJobAfterDelay(jobs, jobId);
+ });
- 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();
- stderrReader.push(chunk);
- });
+ let missingPyModule = null;
+ // Rolling tail of this child's stderr. The Metal abort text is the only
+ // evidence of WHY the watchdog fired and it is not a protocol line, so
+ // nothing else on the path retains it. Bounded so a chatty runtime cannot
+ // 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 recordStderrTail = (raw) => {
+ stderrTail.push(raw);
+ if (stderrTail.length > STDERR_TAIL_LINES) stderrTail.shift();
+ };
- proc.on('close', async (code, signal) => {
- // Flush any final unterminated line each stream buffered (the JSON result,
- // a missing-module trace) BEFORE clearing the watchdogs, so a flush that
- // captures the result JSON and re-arms the completion watchdog is then
- // immediately cancelled by clearCompletionWatchdog() rather than firing a
- // stray SIGKILL during teardown.
- stdoutReader.flush();
- stderrReader.flush();
- clearCompletionWatchdog();
- clearIdleStallTimer();
- activeProcess = null;
- // The child has exited, so its accelerator allocation is gone. Release
- // before emitting the terminal completion event: an extend chain starts its
- // next child from that event and must be able to acquire the machine claim.
- await releaseHeavyClaim();
- // Wrap the whole teardown so a throw from finalizeGeneratedVideo (history
- // save, thumbnail, file move) can't leak as an unhandled rejection — on
- // Node ≥15 that kills the process AND strands the media job `running` with
- // no terminal SSE. The catch routes any failure through the job's error
- // finalizer so the client still gets a terminal 'failed' event.
- try {
- // Cleanup the resized temp images if we made them. Track via flags rather
- // than a path-prefix check — tmpdir() can return a symlinked path
- // (macOS /var → /private/var) so startsWith() can silently miss.
- // Cleanup internally generated resize/reference files, route-staged
- // uploads, and direct-call audio through the same ownership-aware helper.
- await cleanupTempFiles({ includeUploads: true, includeUntrackedAudio: true });
-
- // A PortOS-fired SIGKILL (completion-teardown watchdog OR idle-stall
- // deadline) is a SUCCESS when the output file is already on disk and
- // non-empty — e.g. a runtime that wrote its .mp4 but never printed a
- // recognized completion marker, then hung: the idle timer kills it, but
- // the finished video must be kept, not discarded as "no output". A kill
- // with no output on disk (a genuine pre-output stall, or a marker from a
- // malformed runtime that wrote nothing) still fails loudly below.
- const watchdogSuccess = isWatchdogSuccess({ completionWatchdogFired, idleStallFired, signal, outputPath });
-
- if (code !== 0 && !watchdogSuccess) {
- job.status = 'error';
- let reason;
- if (missingPyModule) {
- const runtimeInfo = BYOV_RUNTIME_INFO[model.runtime];
- if (runtimeInfo) {
- // The probe believed the venv was ready but a runtime import
- // disagreed — drop the cached "ready" so the next /runtime-status
- // re-probes and the install banner re-appears.
- invalidateByovReadyCache(runtimeInfo.id);
- reason = `Python module '${missingPyModule}' is missing from the ${runtimeInfo.label} runtime. Use Install / Repair in Video Gen's model setup panel.`;
+ // The python child's STATUS:/STAGE:/DOWNLOAD:/tqdm → SSE-frame parser lives
+ // in generateVideoHelpers.js so it can be unit-tested without a real child.
+ // Returns true for a recognized progress/status/noise line (suppress raw
+ // logging), false for an unhandled line worth raw-logging.
+ const handleLine = makeVideoGenLineHandler({ job, jobId, pythonNoiseRe: PYTHON_NOISE_RE });
+
+ // Per-stream line readers carry the partial trailing line across chunk
+ // boundaries and decode through a StringDecoder, so a marker (or multibyte
+ // char) split across a pipe chunk can't tear an event — and the final
+ // unterminated line is emitted on 'close' via flush().
+ const stdoutReader = createLineReader((raw) => {
+ const line = raw.trim();
+ if (!line) return;
+ // mlx_video emits one JSON line on stdout when finished — capture it
+ // for the result metadata; otherwise raw-log so we can debug failures.
+ try {
+ const parsed = JSON.parse(line);
+ if (parsed.video_path) {
+ job.resultJson = parsed;
+ // The result JSON is the strongest "work is done" signal — arm the
+ // watchdog so a post-completion teardown hang can't wedge the job.
+ armCompletionWatchdog();
+ }
+ return;
+ } catch { /* not JSON */ }
+ // Some runtimes don't print the result JSON but do log the final
+ // decode+mux line right before they should exit — treat it the same way.
+ if (MUXING_DONE_RE.test(line)) armCompletionWatchdog();
+ console.log(`🐍-out [${jobId.slice(0, 8)}] ${line}`);
+ });
+ const stderrReader = createLineReader((raw) => {
+ recordStderrTail(raw);
+ // Record the root-cause module only — downstream imports in the same
+ // traceback raise the same error against later names.
+ if (!missingPyModule) {
+ const m = raw.match(MODULE_NOT_FOUND_RE);
+ if (m) missingPyModule = m[1];
+ }
+ if (!handleLine(raw)) console.log(`🐍 [${jobId.slice(0, 8)}] ${raw.trim()}`);
+ }, { splitRe: /[\n\r]+/ });
+
+ 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();
+ stdoutReader.push(chunk);
+ });
+
+ 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();
+ stderrReader.push(chunk);
+ });
+
+ // Guards the ONE terminal run of this child's teardown. The relaunch path
+ // may have to drive handleChildClose() by hand (a replacement that died
+ // before its listener was attached), and that must not double-release the
+ // claim, double-clean the temp files, or emit two terminal events if the
+ // real event lands as well.
+ let closeHandled = false;
+ const handleChildClose = async (code, signal) => {
+ if (closeHandled) return;
+ closeHandled = true;
+ // Flush any final unterminated line each stream buffered (the JSON result,
+ // a missing-module trace) BEFORE clearing the watchdogs, so a flush that
+ // captures the result JSON and re-arms the completion watchdog is then
+ // immediately cancelled by clearCompletionWatchdog() rather than firing a
+ // stray SIGKILL during teardown.
+ stdoutReader.flush();
+ stderrReader.flush();
+ clearCompletionWatchdog();
+ clearIdleStallTimer();
+ // The relaunch window opens the instant activeProcess is cleared: until a
+ // replacement child is tracked, cancel() has nothing to kill and silently
+ // reports false. Snapshot the epoch at exactly that boundary so the
+ // relaunch can observe a cancel it otherwise could not see — and so the
+ // guard survives anyone later putting an await between the two.
+ const cancelEpochAtClose = cancelEpoch;
+ activeProcess = null;
+ // One-shot relaunch for a Metal command-buffer watchdog abort that landed
+ // INSIDE the Gemma prompt encoder (issue #4589). Decided here, ahead of
+ // the claim release and the temp-file cleanup below, because a relaunch
+ // has to keep both: it renders the SAME job off the SAME staged inputs and
+ // must not surrender the GPU lane between the two children.
+ if (await maybeRelaunchForPromptEncoding({ code, signal, childKilled: proc.killed, cancelEpochAtClose, stderr: stderrTail.join('\n') })) return;
+ // The child has exited, so its accelerator allocation is gone. Release
+ // before emitting the terminal completion event: an extend chain starts its
+ // next child from that event and must be able to acquire the machine claim.
+ await releaseHeavyClaim();
+ // Wrap the whole teardown so a throw from finalizeGeneratedVideo (history
+ // save, thumbnail, file move) can't leak as an unhandled rejection — on
+ // Node ≥15 that kills the process AND strands the media job `running` with
+ // no terminal SSE. The catch routes any failure through the job's error
+ // finalizer so the client still gets a terminal 'failed' event.
+ try {
+ // Cleanup the resized temp images if we made them. Track via flags rather
+ // than a path-prefix check — tmpdir() can return a symlinked path
+ // (macOS /var → /private/var) so startsWith() can silently miss.
+ // Cleanup internally generated resize/reference files, route-staged
+ // uploads, and direct-call audio through the same ownership-aware helper.
+ await cleanupTempFiles({ includeUploads: true, includeUntrackedAudio: true });
+
+ // A PortOS-fired SIGKILL (completion-teardown watchdog OR idle-stall
+ // deadline) is a SUCCESS when the output file is already on disk and
+ // non-empty — e.g. a runtime that wrote its .mp4 but never printed a
+ // recognized completion marker, then hung: the idle timer kills it, but
+ // the finished video must be kept, not discarded as "no output". A kill
+ // with no output on disk (a genuine pre-output stall, or a marker from a
+ // malformed runtime that wrote nothing) still fails loudly below.
+ const watchdogSuccess = isWatchdogSuccess({ completionWatchdogFired, idleStallFired, signal, outputPath });
+
+ if (code !== 0 && !watchdogSuccess) {
+ job.status = 'error';
+ let reason;
+ if (missingPyModule) {
+ const runtimeInfo = BYOV_RUNTIME_INFO[model.runtime];
+ if (runtimeInfo) {
+ // The probe believed the venv was ready but a runtime import
+ // disagreed — drop the cached "ready" so the next /runtime-status
+ // re-probes and the install banner re-appears.
+ invalidateByovReadyCache(runtimeInfo.id);
+ reason = `Python module '${missingPyModule}' is missing from the ${runtimeInfo.label} runtime. Use Install / Repair in Video Gen's model setup panel.`;
+ } 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) {
+ // Signal → actionable cause (SIGABRT = the macOS Metal command-buffer
+ // watchdog, SIGBUS/SIGSEGV = a native MLX/Metal crash, SIGKILL = OOM),
+ // stamped with the runtime fingerprint that died so the report is
+ // self-documenting. See describeSignalDeath in generateVideoHelpers.js.
+ reason = describeSignalDeath(signal, {
+ fingerprint: await pickDeathFingerprint({ emitted: job.runtime, runtimeId: model.runtime }),
+ });
} else {
- reason = `Python module '${missingPyModule}' is missing. Install it into the configured Python environment and retry.`;
+ reason = `Exit code ${code}`;
}
- } 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) {
- // Signal → actionable cause (SIGABRT = the macOS Metal command-buffer
- // watchdog, SIGBUS/SIGSEGV = a native MLX/Metal crash, SIGKILL = OOM),
- // stamped with the runtime fingerprint that died so the report is
- // self-documenting. See describeSignalDeath in generateVideoHelpers.js.
- reason = describeSignalDeath(signal, {
- fingerprint: await pickDeathFingerprint({ emitted: job.runtime, runtimeId: model.runtime }),
- });
+ console.log(`❌ Video generation failed [${jobId.slice(0, 8)}]: ${reason}`);
+ broadcastSse(job, { type: 'error', error: `Generation failed: ${reason}` });
+ videoGenEvents.emit('failed', { generationId: jobId, error: reason });
} else {
- reason = `Exit code ${code}`;
- }
- console.log(`❌ Video generation failed [${jobId.slice(0, 8)}]: ${reason}`);
- broadcastSse(job, { type: 'error', error: `Generation failed: ${reason}` });
- videoGenEvents.emit('failed', { generationId: jobId, error: reason });
- } else {
- if (watchdogSuccess) {
- const killCause = idleStallFired ? 'idle-stall deadline' : 'completion teardown hang';
- console.log(`⚠️ video child force-killed (${killCause}) — output is intact [${jobId.slice(0, 8)}]`);
+ if (watchdogSuccess) {
+ const killCause = idleStallFired ? 'idle-stall deadline' : 'completion teardown hang';
+ console.log(`⚠️ video child force-killed (${killCause}) — output is intact [${jobId.slice(0, 8)}]`);
+ }
+ await finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta, actualSeed, mutateHistory: mutateVideoHistory });
}
- await finalizeGeneratedVideo({ job, jobId, outputPath, filename, meta, actualSeed, mutateHistory: mutateVideoHistory });
+ } catch (err) {
+ // Finalize/teardown threw — fail the job loudly instead of crashing the
+ // process. The job may already be partway through finalize, so force the
+ // error state and emit the terminal event the client is waiting on.
+ job.status = 'error';
+ console.error(`❌ Video close handler failed [${jobId.slice(0, 8)}]: ${err.message}`);
+ broadcastSse(job, { type: 'error', error: `Generation failed: ${err.message}` });
+ videoGenEvents.emit('failed', { generationId: jobId, error: err.message });
+ } finally {
+ closeJobAfterDelay(jobs, jobId);
+ }
+ };
+ proc.on('close', handleChildClose);
+ return handleChildClose;
+ };
+
+ // Whether a cancel landed while the relaunch was awaiting something, and if so
+ // stop the replacement child. Checked after EVERY await in the relaunch: until
+ // activeProcess points at it, cancel() has no handle on this child and bumping
+ // the epoch is the only trace the cancel leaves.
+ const canceledDuringRelaunch = (cancelEpochAtClose, retryProc) => {
+ if (cancelEpoch === cancelEpochAtClose) return false;
+ // Fall through to the normal failure path, so the job still reports a
+ // terminal event instead of quietly running to completion after a cancel.
+ console.log(`🛑 canceled during the prompt-encode relaunch — stopping the replacement child [${jobId.slice(0, 8)}]`);
+ stopAbandonedRetryChild(retryProc);
+ return true;
+ };
+
+ // Stop a replacement child that was spawned but will never be wired up —
+ // canceled mid-relaunch, or abandoned because a later setup step threw. It has
+ // no close/error listeners by then, so nothing else would ever reap it.
+ // Tolerant of a null handle (the spawn itself threw) and of a kill that throws
+ // on an already-dead PID, because this runs on the failure path of a failure
+ // path and must not replace the real error with its own.
+ const stopAbandonedRetryChild = (child) => {
+ if (!child) return;
+ try {
+ child.kill('SIGTERM');
+ } catch (err) {
+ console.error(`❌ abandoned prompt-encode retry child would not stop [${jobId.slice(0, 8)}]: ${err.message}`);
+ }
+ };
+
+ // Relaunch this render once when the macOS Metal command-buffer watchdog
+ // aborted the child while the Gemma prompt encoder was running, with a lowered
+ // prompt-encode budget so each encoder command buffer finishes inside the
+ // watchdog window. Returns true when a replacement child owns the job (the
+ // caller must then leave the failure path alone), false when the render should
+ // fail normally.
+ //
+ // Everything the render is defined by — jobId, seed, output path, history
+ // metadata, staged source images/audio — is closed over and reused verbatim, so
+ // the relaunch is the same render at a smaller prompt budget, not a new job.
+ // Deliberately NOT gated on a runtime allowlist: the phase markers the decision
+ // reads are emitted by scripts/generate_ltx2.py alone, so every other runtime is
+ // excluded by construction rather than by a list that could drift.
+ const maybeRelaunchForPromptEncoding = async ({ code, signal, childKilled, cancelEpochAtClose, stderr }) => {
+ if (code === 0) return false;
+ // A child PortOS killed on purpose — a user cancel, or either watchdog — is
+ // never a spontaneous Metal abort to recover from, whatever signal it
+ // finally landed on. Without this a cancel that raced an in-flight abort
+ // would be answered by relaunching the render the user just stopped.
+ if (childKilled) return false;
+ const plan = planPromptEncodingRetry({
+ signal,
+ stderr,
+ promptEncodePhase: job.promptEncodePhase,
+ retriesUsed: promptEncodingRetriesUsed,
+ platform: process.platform,
+ });
+ if (!plan) return false;
+ // Runs from a child 'close' handler, outside the Express request lifecycle —
+ // an uncaught throw here would crash the process, and a failed relaunch must
+ // degrade into the normal failure report rather than strand the job.
+ // Declared outside the try so the catch can stop a child that was spawned
+ // before a later step threw — an unwired child has no listeners and nothing
+ // left to reap it. `retryWired` is the cut-off: past that point the child
+ // owns the job and reports its own terminal event, so the catch must leave
+ // it alone.
+ let retryProc = null;
+ let retryWired = false;
+ try {
+ promptEncodingRetriesUsed += 1;
+ const retryArgs = [...args, '--gemma-max-length', String(plan.gemmaMaxLength)];
+ const message = `Metal watchdog aborted the prompt encoder — retrying once at ${plan.gemmaMaxLength} Gemma tokens`;
+ console.log(`♻️ ${message} [${jobId.slice(0, 8)}]`);
+ broadcastSse(job, { type: 'status', message });
+ videoGenEvents.emit('status', { generationId: jobId, message });
+ retryProc = await spawnDetached(bin, retryArgs, {
+ env: childEnv,
+ controlDir: join(PATHS.videos, '.detached', `${jobId}-retry`),
+ cleanup: true,
+ killProcessGroup: runtimeNeedsProcessGroupKill(model.runtime),
+ });
+ if (canceledDuringRelaunch(cancelEpochAtClose, retryProc)) return false;
+ // Both awaits finish BEFORE activeProcess starts pointing at the
+ // replacement, and the two statements that follow them are synchronous.
+ // That ordering is load-bearing twice over:
+ // - cancel() can never reach a child that has no close listener yet, so
+ // no exit can be emitted into the void and strand the job `running`;
+ // - the child therefore cannot run its close handler (and release the
+ // accelerator claim) while this handoff is still in flight, which would
+ // otherwise let the handoff re-write the claim file with a dead PID and
+ // wedge every later render.
+ await heavyClaim.handoffTo?.(retryProc.pid);
+ if (canceledDuringRelaunch(cancelEpochAtClose, retryProc)) return false;
+ activeProcess = retryProc;
+ // Re-stamp the render clock: eta.js calibrates future estimates from
+ // spawn → finalize, and charging the aborted child's wall time to the
+ // render that actually produced the video would poison every later
+ // estimate for this model.
+ job.renderStartedAtMs = Date.now();
+ const handleRetryClose = wireRenderChild(retryProc);
+ retryWired = true;
+ // The handoff above yields to the event loop, so a replacement child that
+ // died in that window emitted its 'close' with nobody listening — the job
+ // would sit `running` forever, holding the accelerator claim. Read the
+ // corpse's exit state and drive the terminal path by hand; the handler is
+ // guarded against a double run, so a real 'close' that also lands is a
+ // no-op.
+ if (retryProc.exitCode !== null || retryProc.signalCode !== null) {
+ console.log(`⚠️ prompt-encode replacement child exited before it was wired [${jobId.slice(0, 8)}]`);
+ await handleRetryClose(retryProc.exitCode, retryProc.signalCode);
}
+ return true;
} catch (err) {
- // Finalize/teardown threw — fail the job loudly instead of crashing the
- // process. The job may already be partway through finalize, so force the
- // error state and emit the terminal event the client is waiting on.
- job.status = 'error';
- console.error(`❌ Video close handler failed [${jobId.slice(0, 8)}]: ${err.message}`);
- broadcastSse(job, { type: 'error', error: `Generation failed: ${err.message}` });
- videoGenEvents.emit('failed', { generationId: jobId, error: err.message });
- } finally {
- closeJobAfterDelay(jobs, jobId);
+ console.error(`❌ prompt-encode retry failed to spawn [${jobId.slice(0, 8)}]: ${err.message}`);
+ // Wired means the child owns the job and will report its own terminal
+ // event, so nothing here may kill it. Unwired, it can never report at all.
+ if (retryWired) return true;
+ stopAbandonedRetryChild(retryProc);
+ // Nothing is running under this job any more; leave the invariant cancel()
+ // reads (activeProcess === the live child, or null) intact.
+ activeProcess = null;
+ return false;
}
- });
+ };
+
+ wireRenderChild(firstProc);
return { jobId, generationId: jobId, filename, mode: 'local', model: modelId };
}
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index c39e71e933..a4b1bdc1a7 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -10,12 +10,18 @@ import { basename, join } from 'path';
import { tmpdir, totalmem } from 'os';
import { randomUUID } from 'crypto';
-const { heavyClaimRelease, mockPrepareLocalMemory } = vi.hoisted(() => ({
+const { heavyClaimRelease, heavyClaimHandoff, mockPrepareLocalMemory } = vi.hoisted(() => ({
heavyClaimRelease: vi.fn(async () => {}),
+ // Repointing the machine claim at the render child's PID. Stubbed rather than
+ // omitted so a test can make it fail, which is how the relaunch path's
+ // spawned-but-never-wired child becomes observable.
+ heavyClaimHandoff: vi.fn(async () => {}),
mockPrepareLocalMemory: vi.fn(async () => ({ unloaded: [], availableGb: 64, totalGb: 64, budgetGb: 64 })),
}));
vi.mock('../../lib/heavyJobClaim.js', () => ({
- claimHeavyLocalJob: vi.fn(async () => ({ ok: true, holder: {}, release: heavyClaimRelease })),
+ claimHeavyLocalJob: vi.fn(async () => ({
+ ok: true, holder: {}, release: heavyClaimRelease, handoffTo: heavyClaimHandoff,
+ })),
}));
vi.mock('../../lib/localMemory.js', () => ({
prepareLocalMemory: mockPrepareLocalMemory,
@@ -3848,3 +3854,407 @@ describe('generateVideo — MiniMax H3 CUDA contract', () => {
expect(args).not.toContain('--offload-profile');
});
});
+
+// ── one-shot prompt-encode relaunch after a Metal watchdog abort (#4589) ─────
+// A real Metal abort can't be produced here, so the child is driven directly:
+// the marker lines and the abort banner are pushed onto its stderr, then it is
+// closed on SIGABRT exactly as the OS would. What is under test is the decision
+// generateVideo makes from that wreckage — relaunch or fail — plus the argv the
+// relaunch carries.
+describe('generateVideo — Gemma prompt-encode watchdog relaunch', () => {
+ const TIMEOUT_ABORT = 'libc++abi: terminating due to uncaught exception of type std::runtime_error: [METAL] Command buffer execution failed: Caused GPU Timeout Error (00000002:kIOGPUCommandBufferCallbackErrorTimeout)';
+ const INTERACTIVITY_ABORT = 'libc++abi: terminating due to uncaught exception: [METAL] Command buffer execution failed: (00000004:kIOGPUCommandBufferCallbackErrorImpactingInteractivity)';
+ const OOM_ABORT = '[METAL] Command buffer execution failed: (00000008:kIOGPUCommandBufferCallbackErrorOutOfMemory)';
+
+ // A child whose stderr and terminal signal the test drives by hand. The
+ // shared makeProc() closes itself on exit 0, which is the opposite of every
+ // case here.
+ const makeDrivenProc = (pid, { failWiring = false } = {}) => {
+ const listeners = {};
+ const onData = {};
+ const proc = {
+ pid,
+ exitCode: null,
+ signalCode: null,
+ killed: false,
+ stdout: {
+ on: vi.fn((event, fn) => {
+ if (failWiring) throw new Error('stdout stream vanished');
+ onData[`stdout:${event}`] = fn;
+ }),
+ },
+ stderr: { on: vi.fn((event, fn) => { onData[`stderr:${event}`] = fn; }) },
+ on(event, fn) { listeners[event] = fn; return proc; },
+ kill: vi.fn(),
+ };
+ return {
+ proc,
+ // The listener that decides whether this child can ever report a terminal
+ // event. Its presence is the whole point of wiring before the handoff.
+ isWired: () => typeof listeners.close === 'function',
+ stderr: (text) => onData['stderr:data']?.(Buffer.from(`${text}\n`)),
+ close: async (code, signal) => {
+ proc.exitCode = code;
+ proc.signalCode = signal;
+ await listeners.close?.(code, signal);
+ },
+ abort: async (signal = 'SIGABRT') => {
+ proc.signalCode = signal;
+ await listeners.close?.(null, signal);
+ },
+ finish: async () => {
+ proc.exitCode = 0;
+ await listeners.close?.(0, null);
+ },
+ };
+ };
+
+ let restorePlatform = () => {};
+ let failures;
+ let onFailed;
+
+ beforeEach(async () => {
+ // The command-buffer watchdog is a macOS construct and generateVideo gates
+ // the relaunch on the real platform, so pin it — otherwise this whole
+ // describe would silently assert "never relaunches" on Windows CI.
+ // Pinned inside the hook, never at module scope: local.js is already
+ // imported by then.
+ const { pinPlatform } = await import('../../lib/testHelper.js');
+ restorePlatform = pinPlatform('darwin');
+ failures = [];
+ onFailed = (payload) => failures.push(payload);
+ videoGenEvents.on('failed', onFailed);
+ });
+
+ afterEach(() => {
+ videoGenEvents.off('failed', onFailed);
+ restorePlatform();
+ });
+
+ const startRender = async (jobId, children) => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
+ spawnMock.mockClear();
+ for (const child of children) spawnMock.mockResolvedValueOnce(child.proc);
+ await generateVideo({
+ jobId,
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx2_unified',
+ prompt: 'a lighthouse in fog',
+ width: 512,
+ height: 512,
+ numFrames: 25,
+ fps: 24,
+ seed: 987654,
+ });
+ return spawnMock;
+ };
+
+ const ltx2Calls = (spawnMock) => spawnMock.mock.calls.filter(([bin]) => isLtx2Python(bin));
+ const flagValue = (args, flag) => args[args.indexOf(flag) + 1];
+
+ it.each([
+ ['the classic timeout signature', TIMEOUT_ABORT],
+ ['the impacting-interactivity signature newer macOS reports', INTERACTIVITY_ABORT],
+ ])('relaunches once at a reduced Gemma budget on %s', async (_label, abort) => {
+ const first = makeDrivenProc(101);
+ const second = makeDrivenProc(102);
+ const spawnMock = await startRender(`pe-${abort.length}`, [first, second]);
+
+ first.stderr('STAGE:encode-prompt');
+ first.stderr(abort);
+ await first.abort();
+
+ const calls = ltx2Calls(spawnMock);
+ expect(calls).toHaveLength(2);
+ const [firstArgs, retryArgs] = calls.map(([, args]) => args);
+ // The original render never carries the flag — the reduced budget exists
+ // only as the mitigation, not as a new default.
+ expect(firstArgs).not.toContain('--gemma-max-length');
+ expect(flagValue(retryArgs, '--gemma-max-length')).toBe('512');
+ // Same render, smaller prompt budget: seed and output must survive verbatim
+ // or the relaunch silently produces a different clip than the user asked for.
+ expect(flagValue(retryArgs, '--seed')).toBe(flagValue(firstArgs, '--seed'));
+ expect(flagValue(retryArgs, '--seed')).toBe('987654');
+ expect(flagValue(retryArgs, '--output')).toBe(flagValue(firstArgs, '--output'));
+ expect(flagValue(retryArgs, '--prompt')).toBe(flagValue(firstArgs, '--prompt'));
+ // The aborted child must not surface as a terminal failure — the job is
+ // still running, on its replacement child.
+ expect(failures).toHaveLength(0);
+
+ await second.finish();
+ });
+
+ // The bypass probe for the phase gate: identical abort, identical signal, one
+ // extra marker line. If the gate were dropped this case would relaunch too.
+ it('does not relaunch once the prompt encode has finished', async () => {
+ const first = makeDrivenProc(103);
+ const spawnMock = await startRender('pe-after-encode', [first]);
+
+ first.stderr('STAGE:encode-prompt');
+ first.stderr('STAGE:encode-prompt-done');
+ first.stderr(TIMEOUT_ABORT);
+ await first.abort();
+
+ expect(ltx2Calls(spawnMock)).toHaveLength(1);
+ expect(failures).toHaveLength(1);
+ expect(failures[0].error).toMatch(/SIGABRT/);
+ });
+
+ // An OOM abort is not a watchdog timeout: a shorter prompt does not fix it,
+ // and relaunching burns another model load on a machine already out of room.
+ it('does not relaunch on an out-of-memory abort inside the encoder', async () => {
+ const first = makeDrivenProc(104);
+ const spawnMock = await startRender('pe-oom', [first]);
+
+ first.stderr('STAGE:encode-prompt');
+ first.stderr(OOM_ABORT);
+ await first.abort();
+
+ expect(ltx2Calls(spawnMock)).toHaveLength(1);
+ expect(failures).toHaveLength(1);
+ });
+
+ it('relaunches at most once — a second abort at the reduced budget fails the job', async () => {
+ const first = makeDrivenProc(105);
+ const second = makeDrivenProc(106);
+ const spawnMock = await startRender('pe-twice', [first, second]);
+
+ first.stderr('STAGE:encode-prompt');
+ first.stderr(TIMEOUT_ABORT);
+ await first.abort();
+ expect(ltx2Calls(spawnMock)).toHaveLength(2);
+
+ second.stderr('STAGE:encode-prompt');
+ second.stderr(TIMEOUT_ABORT);
+ await second.abort();
+
+ expect(ltx2Calls(spawnMock)).toHaveLength(2);
+ expect(failures).toHaveLength(1);
+ });
+
+ it('never relaunches off macOS, where the command-buffer watchdog does not exist', async () => {
+ restorePlatform();
+ const { pinPlatform } = await import('../../lib/testHelper.js');
+ restorePlatform = pinPlatform('win32');
+ const first = makeDrivenProc(107);
+ const spawnMock = await startRender('pe-win32', [first]);
+
+ first.stderr('STAGE:encode-prompt');
+ first.stderr(TIMEOUT_ABORT);
+ await first.abort();
+
+ expect(ltx2Calls(spawnMock)).toHaveLength(1);
+ expect(failures).toHaveLength(1);
+ });
+
+ // A cancel is answered by SIGTERM, so the child normally dies on a signal the
+ // classifier already ignores — but a cancel that RACES an abort already in
+ // flight still arrives as SIGABRT. Relaunching there would restart the render
+ // the user just stopped.
+ it('does not relaunch a child PortOS killed on purpose, even on SIGABRT', async () => {
+ const first = makeDrivenProc(108);
+ const spawnMock = await startRender('pe-killed', [first]);
+
+ first.stderr('STAGE:encode-prompt');
+ first.stderr(TIMEOUT_ABORT);
+ // What killWithEscalation() leaves behind on the handle when cancel() fires.
+ first.proc.killed = true;
+ await first.abort();
+
+ expect(ltx2Calls(spawnMock)).toHaveLength(1);
+ expect(failures).toHaveLength(1);
+ });
+
+ // The relaunch clears activeProcess before it awaits the replacement spawn, so
+ // for that window cancel() has nothing to kill and reports false. The epoch
+ // check is the only thing that notices — without it the replacement child runs
+ // to completion after the user asked to stop.
+ it('abandons the replacement child when a cancel lands during the relaunch spawn', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const { cancel } = await import('./local.js');
+ const spawnMock = vi.mocked(spawnDetached);
+ const first = makeDrivenProc(109);
+ const second = makeDrivenProc(110);
+ spawnMock.mockClear();
+ spawnMock.mockResolvedValueOnce(first.proc);
+ // Cancel from INSIDE the spawn await — the exact window activeProcess is null.
+ spawnMock.mockImplementationOnce(async () => {
+ cancel();
+ return second.proc;
+ });
+ await generateVideo({
+ jobId: 'pe-cancel-race',
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx2_unified',
+ prompt: 'a lighthouse in fog',
+ width: 512,
+ height: 512,
+ numFrames: 25,
+ fps: 24,
+ seed: 987654,
+ });
+
+ first.stderr('STAGE:encode-prompt');
+ first.stderr(TIMEOUT_ABORT);
+ await first.abort();
+
+ // The replacement was spawned, then stopped rather than left running…
+ expect(ltx2Calls(spawnMock)).toHaveLength(2);
+ expect(second.proc.kill).toHaveBeenCalledWith('SIGTERM');
+ // …and the job still reports a terminal failure instead of hanging.
+ expect(failures).toHaveLength(1);
+ });
+
+ // A replacement child that never gets its close listener can never report a
+ // terminal event, so it must not be left running.
+ it('stops the replacement child when wiring it throws', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
+ const first = makeDrivenProc(111);
+ const second = makeDrivenProc(112, { failWiring: true });
+ spawnMock.mockClear();
+ spawnMock.mockResolvedValueOnce(first.proc).mockResolvedValueOnce(second.proc);
+ await generateVideo({
+ jobId: 'pe-wire-throws',
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx2_unified',
+ prompt: 'a lighthouse in fog',
+ width: 512,
+ height: 512,
+ numFrames: 25,
+ fps: 24,
+ seed: 987654,
+ });
+
+ first.stderr('STAGE:encode-prompt');
+ first.stderr(TIMEOUT_ABORT);
+ await first.abort();
+
+ expect(second.proc.kill).toHaveBeenCalledWith('SIGTERM');
+ // The job still ends, reporting the abort that started all this.
+ expect(failures).toHaveLength(1);
+ });
+
+ // The replacement must not be reachable by cancel() until it is wired: an
+ // unwired child killed mid-handoff emits its exit into the void and strands the
+ // job `running`, and its close handler could otherwise release the accelerator
+ // claim while the handoff is still in flight — which would then rewrite the
+ // claim file with a dead PID and wedge every later render.
+ it('finishes the claim handoff before the replacement child is trackable', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
+ const first = makeDrivenProc(113);
+ const second = makeDrivenProc(114);
+ spawnMock.mockClear();
+ spawnMock.mockResolvedValueOnce(first.proc).mockResolvedValueOnce(second.proc);
+ await generateVideo({
+ jobId: 'pe-wire-order',
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx2_unified',
+ prompt: 'a lighthouse in fog',
+ width: 512,
+ height: 512,
+ numFrames: 25,
+ fps: 24,
+ seed: 987654,
+ });
+ // Sampled from inside the handoff — the window where a wired-and-tracked
+ // child could run its close handler against the in-flight claim write.
+ let wiredDuringHandoff = null;
+ heavyClaimHandoff.mockImplementationOnce(async (pid) => {
+ if (pid === 114) wiredDuringHandoff = second.isWired();
+ });
+
+ first.stderr('STAGE:encode-prompt');
+ first.stderr(TIMEOUT_ABORT);
+ await first.abort();
+
+ expect(wiredDuringHandoff).toBe(false);
+ // …and the wiring does land right after, so the replacement can finalize.
+ expect(second.isWired()).toBe(true);
+ await second.finish();
+ expect(failures).toHaveLength(0);
+ });
+
+ // The cancel window does not close when the spawn resolves — the handoff is
+ // awaited too, and activeProcess is still null across it, so cancel() again
+ // leaves nothing behind but the epoch bump.
+ it('abandons the replacement child when a cancel lands during the claim handoff', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const { cancel } = await import('./local.js');
+ const spawnMock = vi.mocked(spawnDetached);
+ const first = makeDrivenProc(115);
+ const second = makeDrivenProc(116);
+ spawnMock.mockClear();
+ spawnMock.mockResolvedValueOnce(first.proc).mockResolvedValueOnce(second.proc);
+ await generateVideo({
+ jobId: 'pe-cancel-handoff',
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx2_unified',
+ prompt: 'a lighthouse in fog',
+ width: 512,
+ height: 512,
+ numFrames: 25,
+ fps: 24,
+ seed: 987654,
+ });
+ heavyClaimHandoff.mockImplementationOnce(async (pid) => {
+ if (pid === 116) cancel();
+ });
+
+ first.stderr('STAGE:encode-prompt');
+ first.stderr(TIMEOUT_ABORT);
+ await first.abort();
+
+ expect(second.proc.kill).toHaveBeenCalledWith('SIGTERM');
+ // Never wired, so it could not have reported anything — the job's terminal
+ // event has to come from the original abort instead.
+ expect(second.isWired()).toBe(false);
+ expect(failures).toHaveLength(1);
+ });
+
+ // The claim handoff yields to the event loop, so a replacement that dies in
+ // that window emits its 'close' before anything is listening. Nothing would
+ // ever reap it: the job would sit `running` forever, still holding the
+ // accelerator claim, with no terminal SSE or queue event.
+ it('reaps a replacement child that died before its listener was attached', async () => {
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
+ const first = makeDrivenProc(117);
+ const second = makeDrivenProc(118);
+ spawnMock.mockClear();
+ spawnMock.mockResolvedValueOnce(first.proc).mockResolvedValueOnce(second.proc);
+ await generateVideo({
+ jobId: 'pe-early-death',
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx2_unified',
+ prompt: 'a lighthouse in fog',
+ width: 512,
+ height: 512,
+ numFrames: 25,
+ fps: 24,
+ seed: 987654,
+ });
+ // Dies during the handoff, and its close() fires into the void — modelled by
+ // setting the exit state without invoking any listener.
+ heavyClaimHandoff.mockImplementationOnce(async (pid) => {
+ if (pid === 118) second.proc.exitCode = 3;
+ });
+
+ first.stderr('STAGE:encode-prompt');
+ first.stderr(TIMEOUT_ABORT);
+ await first.abort();
+
+ expect(failures).toHaveLength(1);
+ expect(failures[0].error).toMatch(/Exit code 3/);
+ expect(heavyClaimRelease).toHaveBeenCalled();
+
+ // …and the real 'close' arriving late — carrying that same exit status —
+ // is absorbed rather than re-running the whole teardown and reporting the
+ // job as failed a second time.
+ await second.close(3, null);
+ expect(failures).toHaveLength(1);
+ expect(heavyClaimRelease).toHaveBeenCalledTimes(1);
+ });
+});