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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: keep a MiniMax H3 clip whose renderer aborts during native teardown (#6501)
[._.]/ Adam Eivy2fb67b75e3ba
diff --git a/server/services/videoGen/generateVideoHelpers.js b/server/services/videoGen/generateVideoHelpers.jsindex 4690a5cb5d..3ec1699aea 100644--- a/server/services/videoGen/generateVideoHelpers.js+++ b/server/services/videoGen/generateVideoHelpers.js@@ -10,7 +10,9 @@import { existsSync, statSync } from 'fs';import { broadcastSse } from '../../lib/sseUtils.js';-import { generateThumbnail, optimizeForStreaming } from '../../lib/ffmpeg.js';+import {+ generateThumbnail, optimizeForStreaming, probeFrameCount, probeVideoDuration,+} from '../../lib/ffmpeg.js';import { formatBytes } from '../../lib/fileUtils.js';import { renderTimingFields } from '../../lib/renderTiming.js';import { videoGenEvents } from './events.js';@@ -505,6 +507,150 @@ export function isWatchdogSuccess({ completionWatchdogFired, signal, outputPath&& existsSync(outputPath) && statSync(outputPath).size > 0;}+// ── verified post-completion native teardown abort (#6501) ──────────────────+//+// The MiniMax H3 MLX runner can finish its render, mux the clip, print the+// `emit_result` completion contract from scripts/_minimax_h3_common.py, and+// THEN abort inside native interpreter teardown. The clip on disk is complete;+// only the interpreter died. Without recognition, that delivered render is+// absent from history and counted against the media queue's repeated-failure+// hold.+//+// This is deliberately the narrowest possible recovery. It is NOT a general+// "the file looks fine, call it a win" rule: an ordinary nonzero exit, a+// missing python module, an idle timeout, a user cancel, a truncated clip and+// a pre-completion crash all keep failing exactly as before.++/**+ * The single runtime this recovery covers. `minimax_h3_cuda` (Windows/Linux+ * diffusers) and `minimax_h3_ref2va` (the signed native release) are excluded+ * by construction rather than by an allowlist that could drift open — neither+ * has the MLX teardown fault, and both must keep their current outcomes.+ */+export const POST_COMPLETION_ABORT_RUNTIME = 'minimax_h3';++/**+ * Signals that can carry a native-interpreter teardown abort. SIGABRT only for+ * now: a bare nonzero exit is an ordinary failure, SIGKILL belongs to the+ * completion watchdog (and to the OOM killer), and SIGSEGV/SIGBUS are real+ * native crashes that can equally well happen mid-render.+ */+const NATIVE_TEARDOWN_SIGNALS = new Set(['SIGABRT']);++/**+ * The cheap synchronous gate: does this child's death even LOOK like the H3+ * MLX teardown abort? Runs before the (async, ffprobe-backed) output+ * verification so an ordinary failure never pays for a probe.+ *+ * `childKilled` is `proc.killed`, i.e. PortOS asked this child to die — a user+ * cancel or either watchdog. A death we caused is never a spontaneous teardown+ * abort to recover from, whatever signal it finally landed on.+ *+ * @param {object} opts+ * @param {string} [opts.runtime] - the render model's runtime id+ * @param {string|null} [opts.signal] - the signal from the child's 'close'+ * @param {boolean} [opts.childKilled] - `proc.killed`+ * @param {string} [opts.platform] - `process.platform` of the host+ * @returns {boolean}+ */+export function isNativeTeardownAbort({ runtime = null, signal = null, childKilled = false, platform = process.platform } = {}) {+ // MLX is Apple-Silicon only, so a Windows/Linux host reporting this runtime+ // is a misconfiguration rather than the fault this recovery knows about.+ if (platform !== 'darwin') return false;+ if (runtime !== POST_COMPLETION_ABORT_RUNTIME) return false;+ if (childKilled) return false;+ return NATIVE_TEARDOWN_SIGNALS.has(signal);+}++// A filesystem whose mtime resolution is whole seconds (rather than APFS/ext4+// nanoseconds) can stamp a file written milliseconds after the spawn with the+// second BEFORE it. One second of slack absorbs that without weakening the+// check that matters — a stale output from an earlier render is minutes old.+const OUTPUT_MTIME_SLACK_MS = 1000;++// The muxer can round a stream's reported length by a frame or two, and the+// container duration of a clip carrying an audio track is not exactly+// frames/fps. Both tolerances stay tight on purpose: the probe exists to+// reject a TRUNCATED clip, which loses far more than this.+const frameTolerance = (expectedFrames) => Math.max(2, Math.ceil(expectedFrames * 0.02));+const durationToleranceSeconds = (expectedSeconds) => Math.max(0.25, expectedSeconds * 0.05);++/**+ * Verify that a post-completion abort really did leave the requested render on+ * disk. Every check must pass; each returns the reason it did not so the caller+ * can log why a teardown abort stayed a failure.+ *+ * The checks, in order of cost:+ * 1. This child reported EVERY expected output by its exact path. The caller+ * collects that evidence per child, so a stray progress sentence, an+ * unrelated path, or a previous child's result cannot satisfy it.+ * 2. The request is measurable — we know when the render started and how many+ * frames at what rate it asked for. Missing any of that is "cannot+ * verify", which is a refusal, never a pass.+ * 3. Each file exists, is non-empty, and was written AFTER this render+ * started. File existence alone is not evidence: a same-named output from+ * an earlier render would satisfy it.+ * 4. ffprobe reads a frame count and a duration consistent with the request.+ * A probe that could not answer (`null` — no ffprobe, unreadable file) is+ * an explicit "unknown" and refuses recovery; it must never collapse into+ * "consistent".+ *+ * @param {object} ctx+ * @param {string[]} ctx.outputPaths - every file this render was asked to write+ * @param {Set<string>} ctx.completedOutputs - paths THIS child reported done+ * @param {number} ctx.startedAtMs - Date.now() stamped just before the spawn+ * @param {number} ctx.expectedFrames - frames the request asked for+ * @param {number} ctx.fps - frame rate the request asked for+ * @returns {Promise<{ ok: boolean, reason?: string }>}+ */+export async function verifyPostCompletionOutputs({ outputPaths, completedOutputs, startedAtMs, expectedFrames, fps }) {+ if (!Array.isArray(outputPaths) || outputPaths.length === 0) {+ return { ok: false, reason: 'the render declared no expected output' };+ }+ const reported = completedOutputs instanceof Set ? completedOutputs : new Set();+ const unreported = outputPaths.filter((path) => !reported.has(path)).length;+ if (unreported > 0) {+ return { ok: false, reason: `${unreported}/${outputPaths.length} expected outputs were never reported complete by this child` };+ }+ if (!Number.isFinite(startedAtMs) || startedAtMs <= 0) {+ return { ok: false, reason: 'the render start time was not recorded' };+ }+ if (!Number.isFinite(expectedFrames) || expectedFrames <= 0 || !Number.isFinite(fps) || fps <= 0) {+ return { ok: false, reason: 'the requested frame count or frame rate is unknown' };+ }+ const expectedSeconds = expectedFrames / fps;+ for (const [index, outputPath] of outputPaths.entries()) {+ const label = outputPaths.length > 1 ? `output ${index + 1}/${outputPaths.length}` : 'the output';+ if (!existsSync(outputPath)) return { ok: false, reason: `${label} is not on disk` };+ let stats;+ // The file can be unlinked between the existsSync above and this stat+ // (cleanup, an external move), and this runs from a child 'close' handler+ // where an uncaught throw would take the process with it.+ try {+ stats = statSync(outputPath);+ } catch (err) {+ return { ok: false, reason: `${label} could not be read: ${err.message}` };+ }+ if (!(stats?.size > 0)) return { ok: false, reason: `${label} is empty` };+ if (!Number.isFinite(stats.mtimeMs) || stats.mtimeMs < startedAtMs - OUTPUT_MTIME_SLACK_MS) {+ return { ok: false, reason: `${label} predates this render` };+ }+ // eslint-disable-next-line no-await-in-loop+ const frames = await probeFrameCount(outputPath);+ if (!Number.isFinite(frames)) return { ok: false, reason: `${label} could not be probed for frames` };+ if (Math.abs(frames - expectedFrames) > frameTolerance(expectedFrames)) {+ return { ok: false, reason: `${label} carries ${frames} frames, not the ${expectedFrames} requested` };+ }+ // eslint-disable-next-line no-await-in-loop+ const seconds = await probeVideoDuration(outputPath);+ if (!Number.isFinite(seconds)) return { ok: false, reason: `${label} could not be probed for duration` };+ if (Math.abs(seconds - expectedSeconds) > durationToleranceSeconds(expectedSeconds)) {+ return { ok: false, reason: `${label} runs ${seconds.toFixed(2)}s, not the ${expectedSeconds.toFixed(2)}s requested` };+ }+ }+ return { ok: true };+}+/*** Hold a freshly spawned render child's terminal event until its real handlers* are wired (#4617).diff --git a/server/services/videoGen/generateVideoHelpers.test.js b/server/services/videoGen/generateVideoHelpers.test.jsindex 13aaa019ac..c2e4b43e0c 100644--- a/server/services/videoGen/generateVideoHelpers.test.js+++ b/server/services/videoGen/generateVideoHelpers.test.js@@ -1,9 +1,9 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { writeFileSync, rmSync } from 'fs';+import { writeFileSync, rmSync, mkdirSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import { EventEmitter } from 'events';-import { makeVideoGenLineHandler, isWatchdogSuccess, finalizeGeneratedVideo, parseByteProgress, formatBytes, formatDownloadMessage, describeSignalDeath, formatRuntimeFingerprint, describeRenderConditioning, isPromptEncodingMetalWatchdog, planPromptEncodingRetry, DEFAULT_GEMMA_MAX_LENGTH, RETRY_GEMMA_MAX_LENGTH, bufferChildExit, RENDER_INPUTS_VERSION, emitCloudRenderStatus, CLOUD_RENDER_PHASE } from './generateVideoHelpers.js';+import { makeVideoGenLineHandler, isWatchdogSuccess, finalizeGeneratedVideo, parseByteProgress, formatBytes, formatDownloadMessage, describeSignalDeath, formatRuntimeFingerprint, describeRenderConditioning, isPromptEncodingMetalWatchdog, planPromptEncodingRetry, DEFAULT_GEMMA_MAX_LENGTH, RETRY_GEMMA_MAX_LENGTH, bufferChildExit, isNativeTeardownAbort, verifyPostCompletionOutputs, POST_COMPLETION_ABORT_RUNTIME, RENDER_INPUTS_VERSION, emitCloudRenderStatus, CLOUD_RENDER_PHASE } from './generateVideoHelpers.js';describe('parseByteProgress', () => {it('parses single byte value (e.g., "2.5G")', () => {@@ -103,7 +103,13 @@ vi.mock('./events.js', () => ({}));// generateVideoHelpers also imports ffmpeg + fs at module top; stub ffmpeg so// the import graph stays light (finalize isn't exercised in this file).-vi.mock('../../lib/ffmpeg.js', () => ({ generateThumbnail: vi.fn(), optimizeForStreaming: vi.fn() }));+const probeMock = vi.hoisted(() => ({ frames: vi.fn(async () => null), duration: vi.fn(async () => null) }));+vi.mock('../../lib/ffmpeg.js', () => ({+ generateThumbnail: vi.fn(),+ optimizeForStreaming: vi.fn(),+ probeFrameCount: probeMock.frames,+ probeVideoDuration: probeMock.duration,+}));const PYTHON_NOISE_RE = /^(Loading|Fetching|tokenizer|Some weights)/;@@ -702,3 +708,118 @@ describe('emitCloudRenderStatus', () => {expect(sse).toHaveBeenCalledTimes(2);});});++// The gates on the post-completion teardown recovery (#6501). The recovery+// itself is asserted end to end in local.test.js; these pin the two things that+// suite cannot reach cheaply — the host/runtime gate (every other runtime and+// every non-macOS host must keep its current outcome, and CI runs on Windows)+// and the frame/duration tolerance that separates "the muxer rounded" from+// "the file is truncated".+describe('isNativeTeardownAbort', () => {+ const ABORT = { runtime: POST_COMPLETION_ABORT_RUNTIME, signal: 'SIGABRT', childKilled: false, platform: 'darwin' };++ it('recognizes the H3 MLX teardown abort', () => {+ expect(isNativeTeardownAbort(ABORT)).toBe(true);+ });++ it.each([+ ['a non-macOS host, where MLX does not run', { platform: 'win32' }],+ ['the CUDA sibling runtime', { runtime: 'minimax_h3_cuda' }],+ ['the native Ref2VA runtime', { runtime: 'minimax_h3_ref2va' }],+ ['another local runtime entirely', { runtime: 'ltx2' }],+ ['a child PortOS killed on purpose', { childKilled: true }],+ ['an OOM/watchdog SIGKILL', { signal: 'SIGKILL' }],+ ['a native crash that can equally land mid-render', { signal: 'SIGSEGV' }],+ ['an ordinary exit with no signal at all', { signal: null }],+ ])('refuses %s', (_label, override) => {+ expect(isNativeTeardownAbort({ ...ABORT, ...override })).toBe(false);+ });++ it('refuses an empty call rather than defaulting open', () => {+ expect(isNativeTeardownAbort()).toBe(false);+ });+});++describe('verifyPostCompletionOutputs', () => {+ const dir = join(tmpdir(), `portos-teardown-${Date.now()}`);+ const outputPath = join(dir, 'clip.mp4');+ const EXPECTED_FRAMES = 124;+ const FPS = 24;+ let startedAtMs;++ const verify = () => verifyPostCompletionOutputs({+ outputPaths: [outputPath],+ completedOutputs: new Set([outputPath]),+ startedAtMs,+ expectedFrames: EXPECTED_FRAMES,+ fps: FPS,+ });++ beforeEach(() => {+ rmSync(dir, { recursive: true, force: true });+ mkdirSync(dir, { recursive: true });+ startedAtMs = Date.now();+ writeFileSync(outputPath, 'mp4-bytes', { flag: 'w' });+ probeMock.frames.mockResolvedValue(EXPECTED_FRAMES);+ probeMock.duration.mockResolvedValue(EXPECTED_FRAMES / FPS);+ });++ it('accepts an exact match', async () => {+ await expect(verify()).resolves.toEqual({ ok: true });+ });++ // The muxer can round a stream's reported length, and a clip carrying audio+ // is not exactly frames/fps long. Neither is a truncated file.+ it.each([+ ['a frame count two off the request', { frames: EXPECTED_FRAMES - 2 }, true],+ ['a duration a hair under the request', { duration: (EXPECTED_FRAMES / FPS) - 0.2 }, true],+ ['a clip missing a third of its frames', { frames: 80 }, false],+ ['a clip cut to a couple of seconds', { duration: 2 }, false],+ ])('%s', async (_label, override, ok) => {+ if (override.frames != null) probeMock.frames.mockResolvedValue(override.frames);+ if (override.duration != null) probeMock.duration.mockResolvedValue(override.duration);+ expect((await verify()).ok).toBe(ok);+ });++ // Sentinel discipline: a probe that could not answer is "unknown", never+ // "consistent" — a host with no ffprobe must not auto-recover every abort.+ it.each([+ ['the frame probe', () => probeMock.frames.mockResolvedValue(null)],+ ['the duration probe', () => probeMock.duration.mockResolvedValue(null)],+ ])('refuses when %s could not answer', async (_label, breakProbe) => {+ breakProbe();+ expect((await verify()).ok).toBe(false);+ });++ it('refuses when the render start was never stamped', async () => {+ startedAtMs = null;+ const verdict = await verify();+ expect(verdict.ok).toBe(false);+ expect(verdict.reason).toMatch(/start time/i);+ });++ it('refuses an output the child never reported by name', async () => {+ const verdict = await verifyPostCompletionOutputs({+ outputPaths: [outputPath],+ completedOutputs: new Set([join(dir, 'someone-elses.mp4')]),+ startedAtMs,+ expectedFrames: EXPECTED_FRAMES,+ fps: FPS,+ });+ expect(verdict.ok).toBe(false);+ expect(verdict.reason).toMatch(/never reported complete/i);+ });++ it('refuses a batch where only some outputs are present', async () => {+ const second = join(dir, 'clip-2.mp4');+ const verdict = await verifyPostCompletionOutputs({+ outputPaths: [outputPath, second],+ completedOutputs: new Set([outputPath, second]),+ startedAtMs,+ expectedFrames: EXPECTED_FRAMES,+ fps: FPS,+ });+ expect(verdict.ok).toBe(false);+ expect(verdict.reason).toMatch(/output 2\/2 is not on disk/);+ });+});diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.jsindex 75dfed439d..14b6d1914e 100644--- a/server/services/videoGen/local.test.js+++ b/server/services/videoGen/local.test.js@@ -235,6 +235,16 @@ vi.mock('../../lib/sseUtils.js', () => ({PYTHON_NOISE_RE: /^\s*$/,}));+// What ffprobe "reads back" from a rendered file. `durationSeconds: null` is+// the real helper's could-not-measure sentinel and must never read as valid.+const probeState = vi.hoisted(() => ({ frames: 25, durationSeconds: null }));+// Held apart from the vi.mock factory for the same reason as fsMockImpl below:+// tests pin these probes for their own scenario and the override outlives them.+const probeMockImpl = vi.hoisted(() => ({+ probeFrameCount: async () => probeState.frames,+ probeVideoDuration: async () => probeState.durationSeconds,+}));+vi.mock('../../lib/ffmpeg.js', async () => ({findFfmpeg: vi.fn(async () => '/usr/bin/ffmpeg'),safeUnder: vi.fn((base, file) => (file ? join(base, file) : null)),@@ -245,8 +255,11 @@ vi.mock('../../lib/ffmpeg.js', async () => ({// Chained renders on a window-continuity runtime probe each chunk's length// and cut the next hop's conditioning window from it. 25 matches the// numFrames the chain tests render, so the prefix math below lands on a- // realistic value.- probeFrameCount: vi.fn(async () => 25),+ // realistic value. `probeState` lets the post-completion teardown tests drive+ // both probes — including the "could not answer" null sentinel — without+ // disturbing that default.+ probeFrameCount: vi.fn(probeMockImpl.probeFrameCount),+ probeVideoDuration: vi.fn(probeMockImpl.probeVideoDuration),trimVideoFromFrame: vi.fn(async (_videoPath, outPath) => ({ ok: true, outPath })),hasAudioStream: vi.fn(async () => false),// The real builder is pure and covered by ffmpeg.test.js; keep it real here@@ -299,21 +312,31 @@ vi.mock('../../lib/hfCache.js', () => ({// cache MISS on a path that then exists after ffmpeg writes it — which is the// only way to reach extractLastFrame's extraction path at all, since a// stat-everything mock otherwise short-circuits on the cache hit.-const fsState = vi.hoisted(() => ({ missOnce: [], candidateCount: null }));-vi.mock('fs', () => ({+// `mtimeMs: null` means "written just now", which is what every pre-existing+// test wants; a test can pin an older stamp to model a stale leftover output.+const fsState = vi.hoisted(() => ({ missOnce: [], candidateCount: null, mtimeMs: null }));+// Held apart from the vi.mock factory so afterEach can put them back: several+// tests below install a whole-suite `mockReturnValue` on existsSync/statSync,+// and vi.clearAllMocks() drops calls but NOT a return-value override — so a+// leaked one silently reshapes the filesystem every later test sees.+const fsMockImpl = vi.hoisted(() => ({// `candidateCount` caps how many anchor candidates 'exist', so a test can// model ffmpeg writing fewer frames than the window asked for.- existsSync: vi.fn((p) => {+ existsSync: (p) => {const s = String(p);if (fsState.candidateCount == null || !s.includes('anchorcand-')) return true;const n = s.match(/cand-(\d+)\.png$/);return n ? Number(n[1]) <= fsState.candidateCount : true;- }),- statSync: vi.fn((p) => {+ },+ statSync: (p) => {const i = fsState.missOnce.findIndex((frag) => String(p).includes(frag));if (i >= 0) { fsState.missOnce.splice(i, 1); return undefined; }- return { size: 1000 };- }),+ return { size: 1000, mtimeMs: fsState.mtimeMs ?? Date.now() };+ },+}));+vi.mock('fs', () => ({+ existsSync: vi.fn(fsMockImpl.existsSync),+ statSync: vi.fn(fsMockImpl.statSync),watch: vi.fn(() => ({ close: vi.fn() })),}));@@ -463,12 +486,24 @@ beforeEach(async () => {({ videoGenEvents } = await import('./events.js'));});-afterEach(() => {+afterEach(async () => {+ // Put the shared filesystem mock back before anything else — a test that+ // pinned existsSync/statSync to a fixed value keeps that override across+ // vi.clearAllMocks(), and the next test inherits its filesystem.+ const { existsSync, statSync } = await import('fs');+ vi.mocked(existsSync).mockImplementation(fsMockImpl.existsSync);+ vi.mocked(statSync).mockImplementation(fsMockImpl.statSync);+ const { probeFrameCount, probeVideoDuration } = await import('../../lib/ffmpeg.js');+ vi.mocked(probeFrameCount).mockImplementation(probeMockImpl.probeFrameCount);+ vi.mocked(probeVideoDuration).mockImplementation(probeMockImpl.probeVideoDuration);byovRevisionState.current = null;byovRevisionState.expectedRevision = null;settingsState.acceptedModelTerms = [];fsState.missOnce = [];fsState.candidateCount = null;+ fsState.mtimeMs = null;+ probeState.frames = 25;+ probeState.durationSeconds = null;spawnState.nextExitCode = null;anchorPick.best = null;vi.clearAllMocks();@@ -5859,3 +5894,215 @@ describe('resident video batches', () => {else expect(proc.kill).not.toHaveBeenCalled();});});++// ── verified post-completion native teardown abort (#6501) ───────────────────+// The MiniMax H3 MLX runner can finish its render, mux the clip, print the+// `emit_result` completion contract from scripts/_minimax_h3_common.py, and THEN+// abort inside native interpreter teardown. The clip on disk is complete; only+// the interpreter died. A real abort can't be produced here, so the child is+// driven directly — the result line goes onto its stdout and it is closed on+// SIGABRT exactly as the OS would. What is under test is the decision+// generateVideo makes from that wreckage, and every way it must still say+// "failed" instead.+describe('generateVideo — post-completion native teardown abort', () => {+ const NUM_FRAMES = 124;+ const FPS = 24;+ let restorePlatform = () => {};+ let completed;+ let failed;++ beforeEach(async () => {+ // MLX is Apple-Silicon only and the recovery is gated on the real platform,+ // so pin it — otherwise this whole describe would silently assert "never+ // recovers" on Windows CI. Pinned in the hook, never at module scope.+ const { pinPlatform } = await import('../../lib/testHelper.js');+ restorePlatform = pinPlatform('darwin');+ settingsState.acceptedModelTerms = [H3_TERMS];+ probeState.frames = NUM_FRAMES;+ probeState.durationSeconds = NUM_FRAMES / FPS;+ completed = vi.fn();+ failed = vi.fn();+ videoGenEvents.on('completed', completed);+ videoGenEvents.on('failed', failed);+ });++ afterEach(() => {+ videoGenEvents.off('completed', completed);+ videoGenEvents.off('failed', failed);+ restorePlatform();+ });++ const makeChild = async () => {+ const { EventEmitter } = await import('node:events');+ const proc = Object.assign(new EventEmitter(), {+ pid: 4321,+ exitCode: null,+ signalCode: null,+ killed: false,+ stdout: new EventEmitter(),+ stderr: new EventEmitter(),+ kill: vi.fn((signal) => { proc.killed = true; proc.signalCode = signal; }),+ });+ return proc;+ };++ // Starts a render against a child the caller then drives by hand.+ const startRender = async ({ jobId, modelId = 'minimax_h3_8bit', numFrames = NUM_FRAMES, batchSize = 1 }) => {+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');+ const proc = await makeChild();+ vi.mocked(spawnDetached).mockResolvedValueOnce(proc);+ await generateVideo({+ jobId,+ prompt: 'a fox watches the rain',+ modelId,+ width: 1344, height: 768, numFrames, fps: FPS, mode: 'text',+ displaySleep: false,+ ...(batchSize > 1 ? { batchSize, seed: 0 } : {}),+ });+ return proc;+ };++ const emitResult = (proc, payload) => proc.stdout.emit('data', Buffer.from(`${JSON.stringify(payload)}\n`));++ const closeChild = async (proc, code, signal) => {+ proc.exitCode = code;+ proc.signalCode = signal;+ proc.emit('close', code, signal);+ };++ it('keeps the verified render when the child aborts in teardown after reporting it done', async () => {+ const jobId = 'h3-teardown-recover';+ const proc = await startRender({ jobId });++ emitResult(proc, { video_path: join(MOCK_PATHS.videos, `${jobId}.mp4`) });+ await closeChild(proc, null, 'SIGABRT');++ await vi.waitFor(() => expect(completed).toHaveBeenCalledTimes(1));+ // Exactly one terminal event, and it is NOT the 'failed' the media queue+ // counts toward its repeated-failure hold.+ expect(failed).not.toHaveBeenCalled();+ expect(completed.mock.calls[0][0]).toMatchObject({ generationId: jobId });++ // One concise teardown warning that names the fault and nothing about this+ // machine — no filesystem path, no host identity.+ const { broadcastSse } = await import('../../lib/sseUtils.js');+ const warnings = vi.mocked(broadcastSse).mock.calls+ .map(([, frame]) => frame)+ .filter((frame) => frame?.type === 'status' && /native teardown/i.test(frame.message || ''));+ expect(warnings).toHaveLength(1);+ expect(warnings[0].message).not.toContain(MOCK_PATHS.videos);+ });++ // Each of these is a bypass probe: the SAME SIGABRT close, with exactly one+ // element of the evidence chain broken. Every one must stay a failure.+ it.each([+ ['no completion result was ever reported (a pre-completion crash)', {+ report: () => {},+ }],+ ['the reported result names some other file', {+ report: (proc) => emitResult(proc, { video_path: join(MOCK_PATHS.videos, 'someone-elses.mp4') }),+ }],+ ['the completion evidence is only a progress sentence', {+ report: (proc) => proc.stdout.emit('data', Buffer.from('[Decoding video + audio + muxing] done in 3.2s\n')),+ }],+ ['the output on disk predates this render', {+ setup: () => { fsState.mtimeMs = Date.now() - 3_600_000; },+ }],+ ['the output is truncated to a fraction of the requested frames', {+ setup: () => { probeState.frames = 40; },+ }],+ ['the output runs short of the requested duration', {+ setup: () => { probeState.durationSeconds = 2; },+ }],+ ['the frame probe could not answer', {+ setup: () => { probeState.frames = null; },+ }],+ ['the duration probe could not answer', {+ setup: () => { probeState.durationSeconds = null; },+ }],+ ])('still fails when %s', async (_label, { setup, report }) => {+ setup?.();+ const jobId = 'h3-teardown-reject';+ const proc = await startRender({ jobId });++ if (report) report(proc);+ else emitResult(proc, { video_path: join(MOCK_PATHS.videos, `${jobId}.mp4`) });+ await closeChild(proc, null, 'SIGABRT');++ await vi.waitFor(() => expect(failed).toHaveBeenCalledTimes(1));+ expect(completed).not.toHaveBeenCalled();+ });++ it('still fails a cancellation that raced an in-flight abort', async () => {+ const jobId = 'h3-teardown-cancel';+ const proc = await startRender({ jobId });++ emitResult(proc, { video_path: join(MOCK_PATHS.videos, `${jobId}.mp4`) });+ // What cancel() leaves behind: PortOS asked this child to die. A death we+ // caused is never a spontaneous teardown abort to recover from, whatever+ // signal it finally lands on.+ proc.kill('SIGTERM');+ await closeChild(proc, null, 'SIGABRT');++ await vi.waitFor(() => expect(failed).toHaveBeenCalledTimes(1));+ expect(completed).not.toHaveBeenCalled();+ });++ it('still fails an ordinary nonzero exit that follows a completion result', async () => {+ const jobId = 'h3-teardown-exit1';+ const proc = await startRender({ jobId });++ emitResult(proc, { video_path: join(MOCK_PATHS.videos, `${jobId}.mp4`) });+ await closeChild(proc, 1, null);++ await vi.waitFor(() => expect(failed).toHaveBeenCalledTimes(1));+ expect(completed).not.toHaveBeenCalled();+ });++ it('does not extend the recovery to another runtime that aborts the same way', async () => {+ probeState.frames = 25;+ probeState.durationSeconds = 25 / FPS;+ const jobId = 'ltx-teardown-abort';+ const proc = await startRender({ jobId, modelId: 'ltx2_unified', numFrames: 25 });++ emitResult(proc, { video_path: join(MOCK_PATHS.videos, `${jobId}.mp4`) });+ await closeChild(proc, null, 'SIGABRT');++ await vi.waitFor(() => expect(failed).toHaveBeenCalledTimes(1));+ expect(completed).not.toHaveBeenCalled();+ });++ it('recovers a warm batch only once every output is accepted and finalized', async () => {+ const { planVideoBatch } = await import('./batch.js');+ const jobId = 'h3-teardown-batch-full';+ const batch = planVideoBatch({ jobId, batchSize: 2, seed: 0 });+ const proc = await startRender({ jobId, batchSize: 2 });++ for (const item of batch) {+ emitResult(proc, { video_path: join(MOCK_PATHS.videos, item.filename), batch_index: item.index, seed: item.seed });+ }+ const { atomicWrite } = await import('../../lib/fileUtils.js');+ await vi.waitFor(() => expect(vi.mocked(atomicWrite).mock.calls.length).toBeGreaterThanOrEqual(2));+ await closeChild(proc, null, 'SIGABRT');++ await vi.waitFor(() => expect(completed).toHaveBeenCalledTimes(1));+ expect(failed).not.toHaveBeenCalled();+ expect(completed.mock.calls[0][0].results).toHaveLength(2);+ });++ it('leaves a partial warm batch failed, with the results it already saved', async () => {+ const { planVideoBatch } = await import('./batch.js');+ const jobId = 'h3-teardown-batch-partial';+ const batch = planVideoBatch({ jobId, batchSize: 2, seed: 0 });+ const proc = await startRender({ jobId, batchSize: 2 });++ emitResult(proc, { video_path: join(MOCK_PATHS.videos, batch[0].filename), batch_index: 0, seed: batch[0].seed });+ const { atomicWrite } = await import('../../lib/fileUtils.js');+ await vi.waitFor(() => expect(vi.mocked(atomicWrite).mock.calls.length).toBeGreaterThanOrEqual(1));+ await closeChild(proc, null, 'SIGABRT');++ await vi.waitFor(() => expect(failed).toHaveBeenCalledTimes(1));+ expect(completed).not.toHaveBeenCalled();+ expect(failed.mock.calls[0][0].results).toHaveLength(1);+ });+});diff --git a/server/services/videoGen/spawnWatch.js b/server/services/videoGen/spawnWatch.jsindex 25bea4ed5c..669bead425 100644--- a/server/services/videoGen/spawnWatch.js+++ b/server/services/videoGen/spawnWatch.js@@ -21,6 +21,8 @@ import {makeVideoGenLineHandler,finalizeGeneratedVideo,isWatchdogSuccess,+ isNativeTeardownAbort,+ verifyPostCompletionOutputs,describeSignalDeath,planPromptEncodingRetry,bufferChildExit,@@ -139,6 +141,14 @@ export async function spawnAndWatchVideo({});} catch { /* preview is best-effort; the final video remains authoritative */ }+ // Every file this render was asked to write, in the order the runner emits+ // them. Job-level (a relaunch renders the SAME outputs), and the yardstick the+ // post-completion teardown recovery below measures a child's result claims+ // against — so "it printed a path" can never stand in for "it printed OUR path".+ const expectedOutputPaths = batch+ ? batch.map((item) => join(PATHS.videos, item.filename))+ : [outputPath];+// ── one render child, fully wired ──────────────────────────────────────────// Everything per-CHILD lives in here — the process handle, the completion watchdog, the// line readers, the close handler — so the same job can be relaunched once@@ -163,6 +173,11 @@ export async function spawnAndWatchVideo({// we only killed a post-completion teardown hang) rather than reporting the// generic "killed, likely OOM" failure.let completionWatchdogFired = false;+ // Which of `expectedOutputPaths` THIS child reported finished, by exact+ // path. Minted per child rather than stamped on `job` — `job` outlives a+ // prompt-encode relaunch, and the dead child's completion claim must never+ // vouch for its replacement's output (#6501).+ const completedOutputs = new Set();const clearCompletionWatchdog = () => {if (completionWatchdog) {clearTimeout(completionWatchdog);@@ -276,6 +291,7 @@ export async function spawnAndWatchVideo({return;}receivedOutputs += 1;+ completedOutputs.add(itemPath);outputTail = outputTail.then(async () => {const thumbnail = await finalizeGeneratedVideo({job, jobId: item.id, outputPath: itemPath, filename: itemFilename,@@ -309,6 +325,10 @@ export async function spawnAndWatchVideo({}if (parsed.video_path) {job.resultJson = parsed;+ // Completion evidence only when the child names the exact file THIS+ // job asked for. An unrelated path still arms the watchdog (the child+ // is clearly past its render) but proves nothing about our output.+ if (expectedOutputPaths.includes(parsed.video_path)) completedOutputs.add(parsed.video_path);// 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();@@ -389,10 +409,37 @@ export async function spawnAndWatchVideo({// disk still fails loudly below.await outputTail;if (batchError) throw batchError;- const watchdogSuccess = (!batch || batchResults.length === batch.length)+ const allOutputsFinalized = !batch || batchResults.length === batch.length;+ const watchdogSuccess = allOutputsFinalized&& isWatchdogSuccess({ completionWatchdogFired, signal, outputPath });+ // Everything below asks the same question twice — did this child die in+ // a way we have not already forgiven? — so name it once.+ const unforgivenExit = code !== 0 && !watchdogSuccess;++ // A VERIFIED post-completion native teardown abort is also a success+ // (#6501): the H3 MLX runner wrote and muxed its clip, printed the+ // emit_result contract naming this job's output, and only then aborted+ // inside native interpreter teardown. Gated hard — this child's own+ // result claim, a freshly written non-empty file, and an ffprobe reading+ // that matches the request. A warm batch recovers only once EVERY output+ // is accepted and finalized; a partial batch stays failed with the+ // results it already saved. The synchronous gate runs first so no+ // ordinary failure pays for a probe.+ let teardownRecovered = false;+ if (unforgivenExit && allOutputsFinalized+ && isNativeTeardownAbort({ runtime: model.runtime, signal, childKilled: proc.killed })) {+ const verdict = await verifyPostCompletionOutputs({+ outputPaths: expectedOutputPaths,+ completedOutputs,+ startedAtMs: job.renderStartedAtMs,+ expectedFrames: parsedNumFrames,+ fps: meta?.fps,+ });+ teardownRecovered = verdict.ok;+ if (!verdict.ok) console.log(`⚠️ teardown abort stays a failure [${jobId.slice(0, 8)}]: ${verdict.reason}`);+ }- if (code !== 0 && !watchdogSuccess) {+ if (unforgivenExit && !teardownRecovered) {job.status = 'error';let reason;const failure = diagnostics.failure({ prompts: [meta?.prompt, meta?.negativePrompt] });@@ -427,6 +474,15 @@ export async function spawnAndWatchVideo({if (watchdogSuccess) {console.log(`⚠️ video child force-killed (completion teardown hang) — output is intact [${jobId.slice(0, 8)}]`);}+ if (teardownRecovered) {+ // One concise, scrubbed warning: names the fault and nothing about+ // this machine or where the file lives. The completion event below+ // is the only terminal event this job emits.+ const message = `The renderer aborted during native teardown after finishing — the verified video was kept (${signal})`;+ console.log(`⚠️ ${message} [${jobId.slice(0, 8)}]`);+ broadcastSse(job, { type: 'status', message });+ videoGenEvents.emit('status', { generationId: jobId, message });+ }if (batch) {if (batchResults.length !== batch.length) throw new Error(`Video batch stopped after ${batchResults.length}/${batch.length} outputs.`);job.status = 'complete';