Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: double-fork media-job children so they survive a pm2 server restart (#1319)

[._.]/ Adam Eivy76a135522b23
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 1430c6a263..5cf1fab5be 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -60,6 +60,8 @@
## Fixed
+- **[issue-1319] LoRA training and video renders now survive a `pm2 restart portos-server` instead of dying mid-run.** A multi-hour LoRA training run kept dying with `SIGINT`/`KeyboardInterrupt` at the exact second portos-server restarted (it restarts routinely on the memory ceiling). Root cause: pm2's `TreeKill` walks the parent→child process tree by **PPID** and signals every descendant of portos-server on restart — and the trainer/render children were descendants. `detached: true` didn't help (it only moves the child to a new process *group*; TreeKill keys on PPID, not the group), and `treekill: false` on the app broke pm2's own reap (lingering `:5555` → EADDRINUSE crash-loop). The fix is spawn-side: a new `spawnDetached` helper (`server/lib/detachedSpawn.js`) **double-forks** the job through a pure-`sh` launcher so it reparents to init (PPID=1) and leaves pm2's tree entirely, while the server keeps streaming progress by tailing on-disk log files (`stdout`/`stderr`/exit-status). Both spawn sites adopt it — `server/services/loraTraining/index.js` (was relying on the ineffective `detached: true`) and `server/services/videoGen/local.js` (which previously had *no* detach at all, so it was fully exposed). Cancel/SIGKILL escalation, the completion watchdog, and `caffeinate` keep-awake all work unchanged (they signal the job by PID, which still reaches the reparented child); video renders clean up their `data/videos/.detached/<jobId>` scratch dir on completion. The raised memory ceiling + checkpoint-resume remain the safety net for the rare restart that lands in the ~1ms pre-detach window. (`server/lib/detachedSpawn.js`, `server/services/loraTraining/index.js`, `server/services/videoGen/local.js`, #1319)
+
- **Object and place LoRA datasets can now override their Lighting/Settings variation axes in the generate-batch dialog.** The object/place LoRA feature was functional server-side (`deriveVariationAxes` applies kind-appropriate lighting/setting defaults), but `LoraDatasetDetail` hard-coded `expressionOptions`/`outfitOptions` to `[]` for non-character kinds, so `GenerateBatchDialog`'s `options.length > 0` guards were always false and the relabeled "Lighting"/"Settings" chip lists never rendered — users could only ever use the server defaults, and the per-kind relabel logic was dead code. The dataset detail now exposes the server-derived axes via a new `GET /api/lora-datasets/:id/variation-axes` endpoint, and the client seeds the chips from that vocab (instead of duplicating the object/place axis constants client-side), so the overrides flow through the existing `expressions`/`outfits` generate params. (`server/services/loraDatasetGenerate.js`, `server/routes/loraDatasets.js`, `client/src/pages/LoraDatasetDetail.jsx`, #1322)
- **The LoRA checkpoint picker no longer shows duplicate cards or offers the untrained step-0 adapter as a "Use this" option.** A run's checkpoint picker could render several identical cards — most visibly three cards all at "step 0" with the same base-model preview. Two pre-existing artifacts caused it: (1) mflux writes a `0000000_checkpoint.zip` from its `num_iterations==0` monitoring block — the *untrained* initial adapter — and `listRunCheckpoints` listed it as deployable even though promoting it is a no-op; (2) every **manual** resume is a fresh job/watcher with an empty `seen` set, so it re-emits checkpoints that already exist and `run.artifacts.checkpoints` accumulates duplicate entries for the same step. `listRunCheckpoints` now collapses to one entry per (filename-derived) step — keeping the record that captured a real loss, tie-breaking on the latest — and drops step 0 entirely, so `promoteCheckpoint(step:0)` correctly returns `CHECKPOINT_NOT_FOUND`. The segmented-training path was never affected (one watcher with a persistent `seen` set spans all segments). (`server/services/loraTraining/checkpoints.js`, #1323)
diff --git a/server/lib/README.md b/server/lib/README.md
index 90a71d3f9e..535203ce5b 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -122,6 +122,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `openFolder.js` | `openFolderInSystemExplorer(localPath)` — cross-platform "open in Finder/Explorer/Nautilus" via detached spawn; child `error` handler prevents spawn failures from crashing the process. |
| `bufferedSpawn.js` | `bufferedSpawn(cmd, args, opts)` (structured non-throwing result) + `bufferedSpawnOrThrow` (throwing adapter), plus `killProcessTree`, `needsShell`, `IS_WIN32`, `WIN_CMD_SHIMS`, `MAX_OUTPUT_BYTES` — shared buffered-spawn machinery with capped stdout/stderr, timeout-kill, and Windows `taskkill /T /F` tree-kill. Used by `appBuilder.js` and `appUpdater.js`. |
| `commandSecurity.js` | Allowlist of safe shell commands. |
+| `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Used by loraTraining + videoGen. |
| `execGit.js` | `execGit` utility imported by `git.js` + worktree manager. |
| `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). |
| `gitArgs.js` | `PROTECTED_BRANCHES`, `validateFilePaths(files)` — pure command-arg builders/validators for `git.js` (reject injection/traversal in staged paths). |
diff --git a/server/lib/detachedSpawn.js b/server/lib/detachedSpawn.js
new file mode 100644
index 0000000000..c3ef4be9b6
--- /dev/null
+++ b/server/lib/detachedSpawn.js
@@ -0,0 +1,274 @@
+// Spawn a long-running media-job child that SURVIVES a `pm2 restart
+// portos-server`.
+//
+// pm2's TreeKill walks the parent→child process tree (`ps -e -o pid=,ppid=`)
+// and SIGINTs every descendant of portos-server on restart/stop — and
+// portos-server restarts routinely (memory ceiling). A multi-hour LoRA trainer
+// or video render spawned as a normal child therefore dies mid-run, losing
+// hours of GPU work to a process completely unrelated to training.
+//
+// `detached: true` does NOT help: it puts the child in a new session/process
+// group (Node calls setsid), but TreeKill keys on PPID, not the process group,
+// so the still-PPID-linked child is found and killed anyway. `treekill: false`
+// on the app makes pm2 fail to reap the old node process (lingers on :5555 →
+// EADDRINUSE crash-loop). So the fix has to happen spawn-side.
+//
+// The trick here is a pure-`sh` double-fork so the actual job process reparents
+// to init (PPID=1) and leaves pm2's tree entirely, while the server keeps
+// streaming its output by tailing on-disk log files:
+//
+// server ──spawn(detached)──▶ outer `sh` (exits within ~1ms)
+// │ `{ … } &` backgrounded subshell
+// ▼
+// supervisor sh (reparents to init when outer
+// │ sh exits — PPID becomes 1)
+// ▼
+// job process (PPID = supervisor)
+//
+// Once the outer `sh` exits, TreeKill walking down from portos-server finds
+// neither the supervisor nor the job. The supervisor `wait`s on the job and
+// records its exit status to a file, so the server can still report success /
+// failure for the lifetime it's up. (`setsid(1)` is unavailable on macOS, so
+// we rely on Node's `detached` for the new session plus reparent-to-init from
+// the double-fork — no external launcher binary needed.)
+//
+// The returned object is ChildProcess-LIKE — it exposes `pid`, `stdout`,
+// `stderr` (EventEmitters emitting `data`/`end`), `on('close', (code,
+// signal))`, `on('error', err)`, `kill(signal)`, `killed`, `exitCode`,
+// `signalCode` — so existing spawn call sites adopt it with minimal change.
+//
+// NOTE: this does NOT re-attach to a job that outlived the server (the poller
+// dies with the process); a restarted server simply stops streaming while the
+// job keeps running, and checkpoint-resume recovers anything in flight.
+// Re-attach is tracked separately (#1332).
+
+import { spawn } from 'child_process';
+import { EventEmitter } from 'events';
+import { constants as osConstants } from 'os';
+import { join } from 'path';
+import { open, readFile, rm, stat } from 'fs/promises';
+import { ensureDir, sleep } from './fileUtils.js';
+
+// Default cadence for tailing the job's log files and polling for completion.
+// 250ms matches the high-frequency-write batching cadence used elsewhere — far
+// below human perception for progress, cheap enough to run for hours.
+const DEFAULT_POLL_MS = 250;
+// How long to wait for the supervisor to write the job's PID before declaring
+// the launch a failure. The supervisor writes it the instant the job spawns;
+// 10s is generous slack for a loaded machine.
+const PID_TIMEOUT_MS = 10000;
+
+// `wait` reports a signal-terminated child as 128+signum. Invert os signal
+// constants once so we can decode that back into Node's ('code', 'signal')
+// close convention (exactly one of the two is non-null).
+const SIGNAL_BY_NUMBER = Object.fromEntries(
+ Object.entries(osConstants.signals).map(([name, num]) => [num, name])
+);
+
+// Double-fork launcher. argv: <controlDir> <bin> <bin-args…> — passed as
+// positional params (NOT interpolated into the script string) so paths/args
+// with spaces or shell metacharacters can't break quoting or inject.
+// $1 → control dir (holds stdout.log/stderr.log/pid/exit)
+// "$@" (after shift) → the job command + its args
+// The `{ … } &` group is a backgrounded subshell; when the outer `sh` hits EOF
+// and exits, that subshell reparents to init, taking the job with it.
+const LAUNCHER = `
+d="$1"; shift
+{
+ "$@" > "$d/stdout.log" 2> "$d/stderr.log" &
+ child=$!
+ printf '%s' "$child" > "$d/pid"
+ wait "$child"
+ printf '%s' "$?" > "$d/exit"
+} &
+`;
+
+/**
+ * Spawn a detached, pm2-restart-surviving child process.
+ *
+ * @param {string} bin - executable to run
+ * @param {string[]} args - arguments
+ * @param {object} opts
+ * @param {object} [opts.env] - child environment
+ * @param {string} [opts.cwd] - working directory for the job
+ * @param {string} opts.controlDir - job-private dir for log/pid/exit files
+ * @param {number} [opts.pollMs] - tail/poll cadence (default 250ms)
+ * @param {boolean} [opts.cleanup] - remove controlDir after the job terminates
+ * (default false — keep the logs, e.g. inside a run dir for post-mortem)
+ * @returns {Promise<object>} ChildProcess-like handle (resolves once the PID is known)
+ */
+export async function spawnDetached(bin, args = [], { env, cwd, controlDir, pollMs = DEFAULT_POLL_MS, cleanup = false } = {}) {
+ if (!controlDir) throw new Error('spawnDetached requires a controlDir');
+ await ensureDir(controlDir);
+ // Clear any stale control files from a prior run reusing this dir, so the
+ // PID/exit pollers can't latch onto a previous job's results.
+ const pidFile = join(controlDir, 'pid');
+ const exitFile = join(controlDir, 'exit');
+ const stdoutLog = join(controlDir, 'stdout.log');
+ const stderrLog = join(controlDir, 'stderr.log');
+ await Promise.all([pidFile, exitFile, stdoutLog, stderrLog].map((f) => rm(f, { force: true })));
+
+ const handle = new EventEmitter();
+ handle.stdout = new EventEmitter();
+ handle.stderr = new EventEmitter();
+ handle.pid = null;
+ handle.killed = false;
+ handle.exitCode = null;
+ handle.signalCode = null;
+
+ // Launch the double-fork. `detached` gives the outer sh its own session;
+ // `stdio: 'ignore'` because all job output is redirected to files by the
+ // launcher; `.unref()` so the server never waits on the (instantly-exiting)
+ // outer sh.
+ const launcher = spawn('sh', ['-c', LAUNCHER, 'sh', controlDir, bin, ...args], {
+ env,
+ cwd,
+ detached: true,
+ stdio: 'ignore',
+ });
+ // The outer sh exits in ~1ms; a spawn error (e.g. no `sh`) is the only real
+ // launcher failure. Capture it so the deferred kickoff below surfaces it as
+ // the handle's 'error' AFTER the caller has attached listeners — emitting it
+ // synchronously here could throw as an unhandled 'error'.
+ let launcherSpawnError = null;
+ launcher.on('error', (err) => { launcherSpawnError = err; });
+ launcher.unref();
+
+ // Tail state: a persistent fd per log (opened lazily once the supervisor
+ // creates the file) plus the byte offset read so far. Holding the fd open for
+ // the job's lifetime avoids an open+close per poll tick (~4/s for hours).
+ const fds = { [stdoutLog]: null, [stderrLog]: null };
+ const offsets = { [stdoutLog]: 0, [stderrLog]: 0 };
+ const emitterFor = { [stdoutLog]: handle.stdout, [stderrLog]: handle.stderr };
+ const CHUNK = 64 * 1024;
+
+ // Read everything appended to a log since the last poll and emit it as 'data'
+ // chunks (Buffers, matching ChildProcess stream semantics). `read` returns
+ // bytesRead, so no per-tick stat is needed to find EOF.
+ const drainLog = async (logPath) => {
+ if (!fds[logPath]) {
+ fds[logPath] = await open(logPath, 'r').catch(() => null);
+ if (!fds[logPath]) return; // file not created yet (job hasn't started writing)
+ }
+ const fh = fds[logPath];
+ for (;;) {
+ const buf = Buffer.alloc(CHUNK);
+ const { bytesRead } = await fh.read(buf, 0, CHUNK, offsets[logPath]);
+ if (bytesRead <= 0) break;
+ offsets[logPath] += bytesRead;
+ emitterFor[logPath].emit('data', buf.subarray(0, bytesRead));
+ if (bytesRead < CHUNK) break;
+ }
+ };
+ // Drain both logs concurrently (independent files/offsets/emitters), never
+ // rejecting so a transient read error can't break the poll loop.
+ const drainBoth = () => Promise.all(
+ [stdoutLog, stderrLog].map((p) => drainLog(p).catch(() => {}))
+ );
+ const closeFds = () => Promise.all(
+ [stdoutLog, stderrLog].map((p) => (fds[p] ? fds[p].close().catch(() => {}) : null))
+ );
+
+ let closed = false;
+ let timer = null;
+ const finish = async () => {
+ if (closed) return;
+ closed = true;
+ if (timer) clearTimeout(timer);
+ // Final drain so the job's last bytes (e.g. the RESULT:/result-JSON line a
+ // hard os._exit can emit just before teardown) are delivered before 'end'.
+ await drainBoth();
+ await closeFds();
+ handle.stdout.emit('end');
+ handle.stderr.emit('end');
+ const raw = await readFile(exitFile, 'utf8').catch(() => '');
+ const status = Number.parseInt(raw, 10);
+ let code = null;
+ let signal = null;
+ if (Number.isFinite(status)) {
+ if (status > 128 && SIGNAL_BY_NUMBER[status - 128]) signal = SIGNAL_BY_NUMBER[status - 128];
+ else code = status;
+ } else {
+ code = 1; // exit file missing/garbled — treat as generic failure
+ }
+ handle.exitCode = code;
+ handle.signalCode = signal;
+ handle.emit('close', code, signal);
+ if (cleanup) rm(controlDir, { recursive: true, force: true }).catch(() => {});
+ };
+
+ // Single poll tick: stream new output, then check for the exit sentinel. The
+ // supervisor writes `exit` only AFTER `wait` returns, by which point the job
+ // has closed its redirected fds — so seeing `exit` guarantees the logs are
+ // complete and the final drain in finish() captures everything. A `stat`
+ // (size>0) tests for the sentinel without allocating/reading the whole file.
+ const tick = async () => {
+ if (closed) return;
+ await drainBoth();
+ const exited = await stat(exitFile).then((s) => s.size > 0).catch(() => false);
+ if (exited) {
+ await finish();
+ return;
+ }
+ timer = setTimeout(() => { tick().catch((err) => handle.emit('error', err)); }, pollMs);
+ };
+
+ // Block until the supervisor records the job PID (the instant the job
+ // spawns), so callers can rely on `handle.pid` right after `await
+ // spawnDetached`. A PID that never appears means the launch itself failed.
+ // We only RESOLVE the pid here; the tailing/error emission is deferred to a
+ // setImmediate after the handle is returned (below) so the caller's
+ // synchronous `.on('data'|'close'|'error')` listeners are attached before
+ // any event can fire — otherwise an immediate emission would be lost (data /
+ // close) or throw as unhandled (error), matching ChildProcess async timing.
+ let launchError = null;
+ const awaitPid = async () => {
+ for (let waited = 0; waited < PID_TIMEOUT_MS; waited += pollMs) {
+ if (launcherSpawnError) { launchError = launcherSpawnError; return; }
+ const raw = await readFile(pidFile, 'utf8').catch(() => '');
+ const pid = Number.parseInt(raw, 10);
+ if (Number.isFinite(pid) && pid > 0) {
+ handle.pid = pid;
+ return;
+ }
+ await sleep(pollMs);
+ }
+ // No PID. If the supervisor still recorded an exit status, the job ran and
+ // exited (e.g. a non-existent bin → 127); route that through 'close'.
+ // Otherwise it's a hard launch failure.
+ const exitRaw = await readFile(exitFile, 'utf8').catch(() => '');
+ if (exitRaw.length === 0) {
+ launchError = new Error(`detached spawn produced no PID within ${PID_TIMEOUT_MS}ms`);
+ }
+ };
+
+ // Signal the job directly by PID (it has reparented away from our tree, but a
+ // direct PID signal still reaches it). Mirrors the original `proc.kill()`
+ // which also signalled the PID, not the group.
+ handle.kill = (signal = 'SIGTERM') => {
+ handle.killed = true;
+ if (!handle.pid) return false;
+ try {
+ process.kill(handle.pid, signal);
+ return true;
+ } catch {
+ return false; // ESRCH — already gone
+ }
+ };
+
+ await awaitPid();
+
+ // Kick off tailing (or the launch-failure path) AFTER returning, so the
+ // caller's synchronous event listeners are wired first.
+ setImmediate(() => {
+ if (launchError) {
+ if (cleanup) rm(controlDir, { recursive: true, force: true }).catch(() => {});
+ handle.emit('error', launchError);
+ return;
+ }
+ if (handle.pid === null) { finish().catch((err) => handle.emit('error', err)); return; }
+ tick().catch((err) => handle.emit('error', err));
+ });
+
+ return handle;
+}
diff --git a/server/lib/detachedSpawn.test.js b/server/lib/detachedSpawn.test.js
new file mode 100644
index 0000000000..d30fa197a1
--- /dev/null
+++ b/server/lib/detachedSpawn.test.js
@@ -0,0 +1,144 @@
+import { describe, it, expect, afterEach } from 'vitest';
+import { mkdtemp, rm, stat } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { execFile } from 'child_process';
+import { promisify } from 'util';
+import { spawnDetached } from './detachedSpawn.js';
+
+const execFileAsync = promisify(execFile);
+const dirs = [];
+const tmpControlDir = async () => {
+ const d = await mkdtemp(join(tmpdir(), 'detached-spawn-'));
+ dirs.push(d);
+ return d;
+};
+afterEach(async () => {
+ await Promise.all(dirs.splice(0).map((d) => rm(d, { recursive: true, force: true })));
+});
+
+// Collect a stream's 'data' chunks into a single string.
+const collect = (emitter) => {
+ let out = '';
+ emitter.on('data', (chunk) => { out += chunk.toString(); });
+ return () => out;
+};
+
+// Resolve when the handle emits 'close' (code, signal) or 'error'.
+const onClose = (handle) => new Promise((resolve, reject) => {
+ handle.on('close', (code, signal) => resolve({ code, signal }));
+ handle.on('error', reject);
+});
+
+describe('spawnDetached', () => {
+ it('streams stdout and stderr, then closes with the exit code', async () => {
+ const controlDir = await tmpControlDir();
+ const handle = await spawnDetached(
+ 'sh',
+ ['-c', 'printf "out-a\\nout-b\\n"; printf "err-1\\n" 1>&2; exit 0'],
+ { controlDir, pollMs: 25 }
+ );
+ const getOut = collect(handle.stdout);
+ const getErr = collect(handle.stderr);
+ const { code, signal } = await onClose(handle);
+ expect(code).toBe(0);
+ expect(signal).toBeNull();
+ expect(getOut()).toBe('out-a\nout-b\n');
+ expect(getErr()).toBe('err-1\n');
+ expect(handle.exitCode).toBe(0);
+ });
+
+ it('propagates a non-zero exit code', async () => {
+ const controlDir = await tmpControlDir();
+ const handle = await spawnDetached('sh', ['-c', 'exit 3'], { controlDir, pollMs: 25 });
+ const { code, signal } = await onClose(handle);
+ expect(code).toBe(3);
+ expect(signal).toBeNull();
+ });
+
+ const ppidOf = async (pid) => {
+ const { stdout } = await execFileAsync('ps', ['-o', 'ppid=', '-p', String(pid)]).catch(() => ({ stdout: '' }));
+ const n = Number.parseInt(stdout.trim(), 10);
+ return Number.isFinite(n) ? n : 0;
+ };
+ // Walk a process's ancestor chain to the root (PPID 1 / 0).
+ const ancestorsOf = async (pid) => {
+ const chain = [];
+ let cur = await ppidOf(pid);
+ while (cur > 1 && chain.length < 50) {
+ chain.push(cur);
+ cur = await ppidOf(cur);
+ }
+ return chain;
+ };
+
+ it('reparents the job out of the spawner tree (escapes pm2 TreeKill)', async () => {
+ const controlDir = await tmpControlDir();
+ const handle = await spawnDetached('sh', ['-c', 'sleep 30'], { controlDir, pollMs: 25 });
+ expect(handle.pid).toBeGreaterThan(0);
+ // The double-fork reparents the supervisor (the job's parent) to init once
+ // the outer sh exits. TreeKill walks DOWN from the spawner's PID, so the
+ // job escapes iff this test process is NOT an ancestor of the job. Poll
+ // briefly to let the outer sh exit, then assert the spawner is absent from
+ // the job's full ancestor chain.
+ let ancestors = [];
+ for (let i = 0; i < 40; i += 1) {
+ ancestors = await ancestorsOf(handle.pid);
+ if (!ancestors.includes(process.pid)) break;
+ await new Promise((r) => setTimeout(r, 25));
+ }
+ expect(ancestors).not.toContain(process.pid);
+ handle.kill('SIGKILL');
+ await onClose(handle);
+ });
+
+ it('kill() signals the reparented job and surfaces the signal on close', async () => {
+ const controlDir = await tmpControlDir();
+ const handle = await spawnDetached('sh', ['-c', 'sleep 30'], { controlDir, pollMs: 25 });
+ expect(handle.pid).toBeGreaterThan(0);
+ // Give the launcher a beat to write the PID file and start the sleeper.
+ await new Promise((r) => setTimeout(r, 50));
+ const killed = handle.kill('SIGKILL');
+ expect(killed).toBe(true);
+ const { code, signal } = await onClose(handle);
+ expect(signal).toBe('SIGKILL');
+ expect(code).toBeNull();
+ expect(handle.signalCode).toBe('SIGKILL');
+ });
+
+ it('rejects (via close=1) when the control dir is reused with stale files cleared', async () => {
+ const controlDir = await tmpControlDir();
+ // First run leaves pid/exit/logs behind.
+ const first = await spawnDetached('sh', ['-c', 'printf "first\\n"; exit 0'], { controlDir, pollMs: 25 });
+ await onClose(first);
+ // Second run on the SAME dir must not latch onto the first run's exit/pid.
+ const second = await spawnDetached('sh', ['-c', 'printf "second\\n"; exit 7'], { controlDir, pollMs: 25 });
+ const getOut = collect(second.stdout);
+ const { code } = await onClose(second);
+ expect(code).toBe(7);
+ expect(getOut()).toBe('second\n');
+ });
+
+ it('removes the control dir after the job ends when cleanup is set', async () => {
+ const controlDir = await tmpControlDir();
+ const handle = await spawnDetached('sh', ['-c', 'printf "x\\n"; exit 0'], { controlDir, pollMs: 25, cleanup: true });
+ await onClose(handle);
+ // finish() schedules the rm after emitting close — give it a tick.
+ await new Promise((r) => setTimeout(r, 50));
+ const present = await stat(controlDir).then(() => true).catch(() => false);
+ expect(present).toBe(false);
+ });
+
+ it('keeps the control dir by default (logs retained for post-mortem)', async () => {
+ const controlDir = await tmpControlDir();
+ const handle = await spawnDetached('sh', ['-c', 'printf "x\\n"; exit 0'], { controlDir, pollMs: 25 });
+ await onClose(handle);
+ await new Promise((r) => setTimeout(r, 50));
+ const present = await stat(controlDir).then(() => true).catch(() => false);
+ expect(present).toBe(true);
+ });
+
+ it('requires a controlDir', async () => {
+ await expect(spawnDetached('sh', ['-c', 'true'], {})).rejects.toThrow(/controlDir/);
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index de7fd77137..6f6b022885 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -112,6 +112,7 @@ export * from './zipStream.js';
export * from './bashResolver.js';
export * from './bufferedSpawn.js';
export * from './commandSecurity.js';
+export * from './detachedSpawn.js';
export * from './execGit.js';
export * from './ffmpeg.js';
export * from './gitArgs.js';
diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.js
index bfbe2aec2c..5eac86892d 100644
--- a/server/services/loraTraining/index.js
+++ b/server/services/loraTraining/index.js
@@ -23,6 +23,7 @@ import { ServerError } from '../../lib/errorHandler.js';
import { v4 as uuidv4 } from '../../lib/uuid.js';
import { hfTokenEnv } from '../../lib/hfToken.js';
import { safeChildProcessEnv } from '../../lib/processEnv.js';
+import { spawnDetached } from '../../lib/detachedSpawn.js';
import { getImageModels } from '../../lib/mediaModels.js';
import { resolveFlux2Python, isFlux2VenvHealthy } from '../../lib/pythonSetup.js';
import { getSettings } from '../settings.js';
@@ -527,18 +528,19 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheck
childEnv.PYTHONUNBUFFERED = '1';
console.log(`🏋️ training [${shortId(jobId)}] spawn ${basename(bin)} ${run.runtime} steps=${run.params.steps} rank=${run.params.rank} images=${manifest.images.length}${resumeCheckpoint ? ` resume=${basename(resumeCheckpoint)}` : ''}`);
- // `detached: true` puts the trainer in its OWN process group. Without it the
- // child sits in the server's group, so when pm2 restarts portos-server — e.g.
- // on the `max_memory_restart` 2 GB ceiling, which a long session crosses
- // routinely — the SIGINT pm2 sends to the group reaches the trainer too and
- // kills it mid-run (observed twice: SIGINT/KeyboardInterrupt at the exact
- // second of a server restart, losing hours of GPU work to a process unrelated
- // to training). Detaching isolates the multi-hour trainer from the server's
- // lifecycle. We still keep `proc` and `proc.kill()` it directly on cancel
- // (signals the child PID, not the group), and DON'T `.unref()` — the queue
- // worker awaits the 'close' event, so the child must keep the worker's
- // promise alive for the run lifecycle.
- const proc = spawn(bin, args, { env: childEnv, stdio: ['ignore', 'pipe', 'pipe'], detached: true });
+ // `spawnDetached` double-forks the trainer so it reparents to init (PPID=1)
+ // and leaves pm2's process tree entirely. A plain `detached: true` child only
+ // gets its OWN process group — but pm2's TreeKill keys on PPID, not the group,
+ // so the still-PPID-linked trainer was found and SIGINT'd anyway whenever
+ // portos-server restarted (e.g. on the memory ceiling, which a long session
+ // crosses routinely — observed twice: SIGINT/KeyboardInterrupt at the exact
+ // second of a server restart, losing hours of GPU work). The detached trainer
+ // streams stdout/stderr through on-disk log files under `<runDir>/.detached`
+ // that the server tails. We still `proc.kill()` it directly by PID on cancel,
+ // and the queue worker awaits the 'close' event for the run lifecycle. No
+ // `cleanup` — those logs are the only copy of raw trainer stdout/stderr, kept
+ // in the run dir for post-mortem and removed when the run dir is deleted.
+ const proc = await spawnDetached(bin, args, { env: childEnv, controlDir: join(dir, '.detached') });
activeProcess = proc;
activeJobId = jobId;
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index 3f618c75a8..4f46afc174 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -18,6 +18,7 @@ import { homedir, tmpdir, totalmem } from 'os';
import { randomUUID } from 'crypto';
import { promisify } from 'util';
import { ensureDir, PATHS, readJSONFile, atomicWrite, UUID_RE } from '../../lib/fileUtils.js';
+import { spawnDetached } from '../../lib/detachedSpawn.js';
import { ServerError } from '../../lib/errorHandler.js';
import { videoGenEvents } from './events.js';
import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_NOISE_RE } from '../../lib/sseUtils.js';
@@ -943,7 +944,20 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
// long inference loops emit nothing to handleLine() for minutes — the UI
// looks dead even when the model is making progress.
childEnv.PYTHONUNBUFFERED = '1';
- const proc = spawn(bin, args, { env: childEnv, stdio: ['ignore', 'pipe', 'pipe'] });
+ // `spawnDetached` double-forks the render child so it reparents to init
+ // (PPID=1) and leaves pm2's process tree — without this a `pm2 restart
+ // portos-server` (e.g. on the memory ceiling) SIGINTs the in-flight render
+ // mid-inference, since pm2's TreeKill walks PPIDs. (This child previously had
+ // no detach at all, so it was fully exposed.) Output streams through on-disk
+ // log files under `data/videos/.detached/<jobId>` that the server tails; we
+ // 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.
+ const proc = await spawnDetached(bin, args, {
+ env: childEnv,
+ controlDir: join(PATHS.videos, '.detached', jobId),
+ cleanup: true,
+ });
activeProcess = proc;
// Panel-side completion watchdog. Armed once we see the render's completion
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index df2cd342fe..b3aae6ed52 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -82,10 +82,12 @@ vi.mock('fs/promises', () => ({
copyFile: vi.fn(async () => {}),
}));
-// Spawn mock — returns a fake EventEmitter-like process that completes
-// immediately with exit code 0.
-vi.mock('child_process', () => {
- const makeProc = () => {
+// Fake EventEmitter-like process that completes immediately with exit code 0.
+// Shared shape for both the child_process spawn mock (ffmpeg/probe) and the
+// detachedSpawn mock (the render child). Hoisted so the vi.mock factories
+// (themselves hoisted above normal declarations) can reference it.
+const { makeProc } = vi.hoisted(() => ({
+ makeProc: () => {
const listeners = {};
const proc = {
pid: 12345,
@@ -103,12 +105,20 @@ vi.mock('child_process', () => {
listeners.close?.(0, null);
});
return proc;
- };
- return {
- spawn: vi.fn(() => makeProc()),
- execFile: vi.fn((_bin, _args, _opts, cb) => cb?.(null, '', '')),
- };
-});
+ },
+}));
+
+vi.mock('child_process', () => ({
+ spawn: vi.fn(() => makeProc()),
+ execFile: vi.fn((_bin, _args, _opts, cb) => cb?.(null, '', '')),
+}));
+
+// The render child now goes through spawnDetached (double-fork survival of a
+// pm2 restart). Mock it to the same fake proc, async since spawnDetached
+// resolves once the PID is known.
+vi.mock('../../lib/detachedSpawn.js', () => ({
+ spawnDetached: vi.fn(async () => makeProc()),
+}));
// ─── module under test ───────────────────────────────────────────────────────
// Import AFTER all vi.mock calls so the hoisted mocks are in place.
@@ -355,9 +365,10 @@ describe('generateChainedVideo — extend chain arg routing', () => {
describe('generateVideo — ltx2 FFLF image resizing', () => {
it('resizes both start and end frames before passing them to the ltx2 helper', async () => {
- const { execFile, spawn } = await import('child_process');
+ const { execFile } = await import('child_process');
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
const execFileMock = vi.mocked(execFile);
- const spawnMock = vi.mocked(spawn);
+ const spawnMock = vi.mocked(spawnDetached);
execFileMock.mockClear();
spawnMock.mockClear();
@@ -407,8 +418,8 @@ describe('generateVideo — PORTOS_T2V_TWO_STAGE arg threading', () => {
// Node-side override + --stage2-steps threading is observable end-to-end
// (the pure-helper test can't see buildLtx2Args).
const renderArgsFor = async (jobId) => {
- const { spawn } = await import('child_process');
- const spawnMock = vi.mocked(spawn);
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
spawnMock.mockClear();
await generateVideo({
jobId,
@@ -647,10 +658,7 @@ describe('generateVideo — panel-side completion watchdog', () => {
};
}
- let restoreSpawn;
beforeEach(async () => {
- const { spawn } = await import('child_process');
- restoreSpawn = vi.mocked(spawn).getMockImplementation();
vi.useFakeTimers();
});
@@ -665,9 +673,9 @@ describe('generateVideo — panel-side completion watchdog', () => {
vi.resetModules();
({ generateVideo } = await import('./local.js'));
- const { spawn } = await import('child_process');
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
const hang = makeHangingProc();
- vi.mocked(spawn).mockImplementationOnce(() => hang.proc);
+ vi.mocked(spawnDetached).mockImplementationOnce(async () => hang.proc);
generateVideo({
jobId: 'watchdog-json-hang',
@@ -699,9 +707,9 @@ describe('generateVideo — panel-side completion watchdog', () => {
vi.resetModules();
({ generateVideo } = await import('./local.js'));
- const { spawn } = await import('child_process');
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
const hang = makeHangingProc();
- vi.mocked(spawn).mockImplementationOnce(() => hang.proc);
+ vi.mocked(spawnDetached).mockImplementationOnce(async () => hang.proc);
generateVideo({
jobId: 'watchdog-mux-hang',
@@ -730,9 +738,9 @@ describe('generateVideo — panel-side completion watchdog', () => {
vi.mocked(existsSync).mockReturnValue(true);
vi.mocked(statSync).mockReturnValue({ size: 1000 });
- const { spawn } = await import('child_process');
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
const hang = makeHangingProc();
- vi.mocked(spawn).mockImplementationOnce(() => hang.proc);
+ vi.mocked(spawnDetached).mockImplementationOnce(async () => hang.proc);
const events = [];
const onCompleted = (e) => events.push(['completed', e]);
@@ -773,9 +781,9 @@ describe('generateVideo — panel-side completion watchdog', () => {
({ generateVideo } = await import('./local.js'));
({ videoGenEvents } = await import('./events.js'));
- const { spawn } = await import('child_process');
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
const hang = makeHangingProc();
- vi.mocked(spawn).mockImplementationOnce(() => hang.proc);
+ vi.mocked(spawnDetached).mockImplementationOnce(async () => hang.proc);
const events = [];
const onCompleted = (e) => events.push(['completed', e]);
@@ -810,9 +818,9 @@ describe('generateVideo — panel-side completion watchdog', () => {
vi.resetModules();
({ generateVideo } = await import('./local.js'));
- const { spawn } = await import('child_process');
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
const hang = makeHangingProc();
- vi.mocked(spawn).mockImplementationOnce(() => hang.proc);
+ vi.mocked(spawnDetached).mockImplementationOnce(async () => hang.proc);
generateVideo({
jobId: 'watchdog-clean-exit',
@@ -842,9 +850,9 @@ describe('generateVideo — panel-side completion watchdog', () => {
vi.resetModules();
({ generateVideo } = await import('./local.js'));
- const { spawn } = await import('child_process');
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
const hang = makeHangingProc();
- vi.mocked(spawn).mockImplementationOnce(() => hang.proc);
+ vi.mocked(spawnDetached).mockImplementationOnce(async () => hang.proc);
generateVideo({
jobId: 'watchdog-no-marker',
@@ -866,8 +874,8 @@ describe('generateVideo — panel-side completion watchdog', () => {
describe('generateVideo — video LoRA (--user-loras) arg threading', () => {
it('emits --user-loras JSON with resolved path + strength for ltx2 renders', async () => {
- const { spawn } = await import('child_process');
- const spawnMock = vi.mocked(spawn);
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
spawnMock.mockClear();
await generateVideo({
@@ -893,8 +901,8 @@ describe('generateVideo — video LoRA (--user-loras) arg threading', () => {
});
it('defaults missing scale to 1.0', async () => {
- const { spawn } = await import('child_process');
- const spawnMock = vi.mocked(spawn);
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
spawnMock.mockClear();
await generateVideo({
@@ -915,8 +923,8 @@ describe('generateVideo — video LoRA (--user-loras) arg threading', () => {
});
it('omits --user-loras when no LoRAs are passed', async () => {
- const { spawn } = await import('child_process');
- const spawnMock = vi.mocked(spawn);
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
spawnMock.mockClear();
await generateVideo({
@@ -935,8 +943,8 @@ describe('generateVideo — video LoRA (--user-loras) arg threading', () => {
});
it('routes a bf16 mlx_video LTX model through the generate_av_lora.py wrapper with --user-loras', async () => {
- const { spawn } = await import('child_process');
- const spawnMock = vi.mocked(spawn);
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
spawnMock.mockClear();
await generateVideo({
@@ -968,8 +976,8 @@ describe('generateVideo — video LoRA (--user-loras) arg threading', () => {
});
it('a non-LoRA mlx_video render still uses the bare generate_av module (no wrapper)', async () => {
- const { spawn } = await import('child_process');
- const spawnMock = vi.mocked(spawn);
+ const { spawnDetached } = await import('../../lib/detachedSpawn.js');
+ const spawnMock = vi.mocked(spawnDetached);
spawnMock.mockClear();
await generateVideo({