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: re-attach a detached LoRA trainer that outlived a server restart instead of failing the run (#1332)
Adam Eivy77072d16d9cf
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 8680ccc3b0..b6fa3f6545 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -85,6 +85,8 @@- **[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. Because a surviving child outlives the server, boot reconcile now **reaps** any still-running orphan (clean `SIGTERM` so the trainer checkpoints, then `SIGKILL`) before marking its run/job failed — and `resumeTrainingRun` reaps too — so a restart becomes a clean checkpointed stop instead of a mid-op `SIGINT` crash, and a resume can never spawn a second trainer into the same checkpoint dir. (Full re-attach-and-finalize across a restart is tracked in #1332.) 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`, `server/services/mediaJobQueue/index.js`, #1319)+- **[issue-1332] A LoRA trainer that outlived a `pm2 restart portos-server` is now re-attached and finalized instead of being killed mid-run.** #1319 made the detached trainer *survive* a server restart, but boot reconcile still **reaped** (clean `SIGTERM` → checkpoint → `SIGKILL`) any survivor before marking its run failed — so a run that was 95% done, or that even *finished* during the few seconds the server was down, registered no LoRA and silently discarded hours of GPU work (the survivor's terminal `RESULT:` line was never read). On boot PortOS now probes whether each interrupted training run's detached child is still alive (or finished-but-unconsumed) and, when it is, **re-attaches**: the media-job queue re-enqueues the run flagged for re-attach (so it reclaims the GPU lane ahead of any new render and won't OOM against a competing job), and `runTraining` tails the survivor's existing on-disk logs from the start — replaying the whole stream through the same line-handler/finalize path a fresh spawn uses, so the run streams live progress again and registers its LoRA exactly as if the server had never restarted. A survivor that genuinely died (killed mid-run with no recorded exit) still falls back to the prior reap-and-fail path, leaving its newest checkpoint resumable. Implemented as `reattachDetached`/`isReattachable` in `server/lib/detachedSpawn.js` (the streaming half of `spawnDetached` without the spawn), `hasSurvivingTrainer` + a `reattach` branch in `server/services/loraTraining/index.js`, and a per-job re-attach decision in `server/services/mediaJobQueue/index.js` boot reconcile; progress persistence is now idempotent so the replay can't double-list checkpoints/samples. (`server/lib/detachedSpawn.js`, `server/services/loraTraining/index.js`, `server/services/mediaJobQueue/index.js`, #1332)+- **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.mdindex 94f97f29b0..b19b2b20bb 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -122,7 +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. |+| `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. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart (boot re-attach, #1332) and `reapDetached` to checkpoint-kill one when re-attach isn't possible. || `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.jsindex 731e289ad1..32750971f3 100644--- a/server/lib/detachedSpawn.js+++ b/server/lib/detachedSpawn.js@@ -37,10 +37,11 @@// 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).+// A restarted server can RE-ATTACH to a survivor via reattachDetached(): the+// control dir's log/pid/exit files outlive the process, so a fresh tailer+// streams the (already-written + still-arriving) output and emits 'close' when+// the supervisor records the exit status — exactly as if the original handle+// had never gone away (#1332).import { spawn } from 'child_process';import { EventEmitter } from 'events';@@ -88,85 +89,26 @@ d="$1"; shift`;/**- * Spawn a detached, pm2-restart-surviving child process.+ * Build the log-tailer for a spawnDetached control dir. Holds a persistent fd+ * per log (opened lazily once the supervisor creates the file) plus the byte+ * offset read so far, streams new bytes as stdout/stderr 'data', and emits the+ * handle's 'close' once the supervisor's `exit` sentinel appears. Shared by the+ * initial spawn and by reattachDetached so both stream identically.*- * @param {string} bin - executable to run- * @param {string[]} args - arguments+ * @param {object} handle - ChildProcess-like handle with `stdout`/`stderr` EventEmitters* @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)+ * @param {string} opts.controlDir - dir holding stdout.log/stderr.log/exit+ * @param {number} opts.pollMs - tail/poll cadence+ * @param {boolean} opts.cleanup - rm the controlDir once the job terminates+ * @returns {{ tick: () => Promise<void>, finish: () => Promise<void> }}*/-export async function spawnDetached(bin, args = [], { env, cwd, controlDir, pollMs = DEFAULT_POLL_MS, cleanup = false } = {}) {- if (!controlDir) throw new Error('spawnDetached requires a controlDir');-- // Windows has no POSIX `sh` for the double-fork, and pm2's process management- // there is taskkill-based rather than the PPID-walk this works around. Fall- // back to a normal child process: a real ChildProcess already satisfies the- // handle contract (pid / stdout / stderr / on('close',code,signal) / kill /- // exitCode / signalCode), so callers are unaffected. Surviving a pm2 restart- // is a POSIX-only guarantee; Windows keeps its prior spawn semantics.- if (process.platform === 'win32') {- return spawn(bin, args, { env, cwd, stdio: ['ignore', 'pipe', 'pipe'] });- }-- const handle = new EventEmitter();- handle.stdout = new EventEmitter();- handle.stderr = new EventEmitter();- handle.pid = null;- handle.killed = false;- handle.exitCode = null;- handle.signalCode = null;- // Default no-op so a setup failure (below) returns a usable handle.- handle.kill = () => false;-- const pidFile = join(controlDir, 'pid');+function createLogTailer(handle, { controlDir, pollMs, cleanup }) {const exitFile = join(controlDir, 'exit');const stdoutLog = join(controlDir, 'stdout.log');const stderrLog = join(controlDir, 'stderr.log');- // Setup is filesystem I/O that can fail (permissions, a stale non-dir path,- // disk full). Surface those as the handle's 'error' event — like a real- // ChildProcess spawn failure — rather than rejecting: callers attach- // `on('error')` AFTER the await for their finalization/cleanup, and a reject- // would bypass that and strand a `running` run or leak temp files. Deferred- // so the listener is attached before it fires.- const ensureControlDir = await ensureDir(controlDir).then(- () => Promise.all([pidFile, exitFile, stdoutLog, stderrLog].map((f) => rm(f, { force: true }))),- ).then(() => null, (err) => err);- if (ensureControlDir) {- setImmediate(() => {- if (cleanup) rm(controlDir, { recursive: true, force: true }).catch(() => {});- handle.emit('error', ensureControlDir);- });- return handle;- }-- // 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).+ // Persistent fd per log + 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 };@@ -243,6 +185,92 @@ export async function spawnDetached(bin, args = [], { env, cwd, controlDir, polltimer = setTimeout(() => { tick().catch((err) => handle.emit('error', err)); }, pollMs);};+ return { tick, finish };+}++/**+ * 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');++ // Windows has no POSIX `sh` for the double-fork, and pm2's process management+ // there is taskkill-based rather than the PPID-walk this works around. Fall+ // back to a normal child process: a real ChildProcess already satisfies the+ // handle contract (pid / stdout / stderr / on('close',code,signal) / kill /+ // exitCode / signalCode), so callers are unaffected. Surviving a pm2 restart+ // is a POSIX-only guarantee; Windows keeps its prior spawn semantics.+ if (process.platform === 'win32') {+ return spawn(bin, args, { env, cwd, stdio: ['ignore', 'pipe', 'pipe'] });+ }++ const handle = new EventEmitter();+ handle.stdout = new EventEmitter();+ handle.stderr = new EventEmitter();+ handle.pid = null;+ handle.killed = false;+ handle.exitCode = null;+ handle.signalCode = null;+ // Default no-op so a setup failure (below) returns a usable handle.+ handle.kill = () => false;++ const pidFile = join(controlDir, 'pid');+ const exitFile = join(controlDir, 'exit');+ const stdoutLog = join(controlDir, 'stdout.log');+ const stderrLog = join(controlDir, 'stderr.log');++ // Setup is filesystem I/O that can fail (permissions, a stale non-dir path,+ // disk full). Surface those as the handle's 'error' event — like a real+ // ChildProcess spawn failure — rather than rejecting: callers attach+ // `on('error')` AFTER the await for their finalization/cleanup, and a reject+ // would bypass that and strand a `running` run or leak temp files. Deferred+ // so the listener is attached before it fires.+ const ensureControlDir = await ensureDir(controlDir).then(+ () => Promise.all([pidFile, exitFile, stdoutLog, stderrLog].map((f) => rm(f, { force: true }))),+ ).then(() => null, (err) => err);+ if (ensureControlDir) {+ setImmediate(() => {+ if (cleanup) rm(controlDir, { recursive: true, force: true }).catch(() => {});+ handle.emit('error', ensureControlDir);+ });+ return handle;+ }++ // 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 the on-disk log files and watch for the supervisor's exit sentinel,+ // streaming new bytes as stdout/stderr 'data' and emitting 'close' on exit.+ // Factored out so reattachDetached (boot re-attach to a survivor — #1332) can+ // drive the exact same streaming machinery against an existing control dir.+ const { tick, finish } = createLogTailer(handle, { controlDir, pollMs, cleanup });+// 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.@@ -307,6 +335,92 @@ const isAlive = (pid) => {try { process.kill(pid, 0); return true; } catch { return false; }};+/**+ * Cheap boot-time probe: is there a detached child worth re-attaching to under+ * this control dir? True when the recorded PID is still alive (job still+ * running) OR the supervisor wrote an `exit` status the previous process never+ * got to consume (job finished during the downtime — its RESULT line is still+ * sitting in the logs unprocessed). False when no PID was recorded, or the PID+ * is dead with no exit sentinel (killed mid-run — nothing clean to resume from,+ * the caller should fall back to reap+fail). Lets a caller decide reattach-vs-+ * fail without constructing a full handle.+ *+ * @param {string} controlDir - the job's spawnDetached control dir+ * @returns {Promise<boolean>}+ */+export async function isReattachable(controlDir) {+ const pidRaw = await readFile(join(controlDir, 'pid'), 'utf8').catch(() => '');+ const pid = Number.parseInt(pidRaw, 10);+ if (!Number.isFinite(pid) || pid <= 0) return false;+ const exitWritten = (await readFile(join(controlDir, 'exit'), 'utf8').catch(() => '')).length > 0;+ return exitWritten || isAlive(pid);+}++/**+ * Re-attach to a detached job that outlived the server (#1332). Returns a fresh+ * ChildProcess-like handle that tails the existing control-dir logs FROM THE+ * START — replaying everything written before the restart and then streaming+ * anything still arriving — and emits 'close' once the supervisor's exit+ * sentinel appears. This is the streaming half of spawnDetached without the+ * spawn: the survivor reparented to init, so we never had (and don't need) a+ * child handle to it; the on-disk logs are the channel.+ *+ * Replaying from offset 0 means the consumer's line handler sees the FULL+ * output — including the terminal `RESULT:{…}` line that registers the trained+ * artifact — so a run that completes during the downtime still finalizes+ * instead of being silently discarded. (Consumers that persist per-line+ * artifacts must therefore be idempotent against a replay.)+ *+ * Returns null when there's nothing safe to attach to (no recorded PID, or a+ * dead PID with no exit sentinel) — the caller should reap+fail instead. The+ * `cleanup` default is false: a re-attached run's logs are its only post-mortem+ * record, same as the original spawn.+ *+ * @param {string} controlDir - the job's spawnDetached control dir+ * @param {object} [opts]+ * @param {number} [opts.pollMs] - tail/poll cadence (default 250ms)+ * @param {boolean} [opts.cleanup] - rm the controlDir once the job terminates+ * @returns {Promise<object|null>} ChildProcess-like handle, or null if not reattachable+ */+export async function reattachDetached(controlDir, { pollMs = DEFAULT_POLL_MS, cleanup = false } = {}) {+ // Detached survival is a POSIX-only guarantee (see spawnDetached's win32+ // fallback) — there is never a reparented orphan to re-attach to on Windows.+ if (process.platform === 'win32') return null;+ const pidRaw = await readFile(join(controlDir, 'pid'), 'utf8').catch(() => '');+ const pid = Number.parseInt(pidRaw, 10);+ if (!Number.isFinite(pid) || pid <= 0) return null;+ const exitWritten = (await readFile(join(controlDir, 'exit'), 'utf8').catch(() => '')).length > 0;+ // Dead PID with no exit sentinel → killed mid-run; nothing clean to stream+ // (the RESULT line was never written). Let the caller reap+fail.+ if (!exitWritten && !isAlive(pid)) return null;++ const handle = new EventEmitter();+ handle.stdout = new EventEmitter();+ handle.stderr = new EventEmitter();+ handle.pid = pid;+ handle.killed = false;+ handle.exitCode = null;+ handle.signalCode = null;+ // Signal the survivor directly by PID (it reparented away from our tree, but+ // a direct PID signal still reaches it) — mirrors spawnDetached's handle.kill+ // so cancel/stall paths work identically on a re-attached run.+ handle.kill = (signal = 'SIGTERM') => {+ handle.killed = true;+ try {+ process.kill(pid, signal);+ return true;+ } catch {+ return false; // ESRCH — already gone+ }+ };++ const { tick } = createLogTailer(handle, { controlDir, pollMs, cleanup });+ // Defer the first tick so the caller's synchronous .on('data'|'close'|'error')+ // listeners are wired before any event fires (matches spawnDetached timing).+ setImmediate(() => { tick().catch((err) => handle.emit('error', err)); });+ return handle;+}+/*** Reap a detached job that outlived the server (boot recovery). Because* spawnDetached children reparent to init, a `pm2 restart` leaves them running@@ -317,7 +431,11 @@ const isAlive = (pid) => {* with it). SIGTERM first so the trainer/render checkpoints, then escalate to* SIGKILL after the grace window — turning a restart from a mid-op SIGINT* crash into a clean checkpointed stop the existing resume path recovers from.- * (Full re-attach instead of reap is tracked in #1332.)+ * This is the fallback when reattachDetached can't (or shouldn't) re-attach —+ * e.g. a render lane with no re-attach path, or a probe that came back+ * non-reattachable. A caller that CAN re-attach (LoRA training, #1332) should+ * prefer reattachDetached so a still-healthy run keeps going rather than being+ * checkpoint-killed.** @param {string} controlDir - the job's spawnDetached control dir* @returns {Promise<{reaped: boolean, pid?: number}>}diff --git a/server/lib/detachedSpawn.test.js b/server/lib/detachedSpawn.test.jsindex 4a6dd5beef..20f466f413 100644--- a/server/lib/detachedSpawn.test.js+++ b/server/lib/detachedSpawn.test.js@@ -4,7 +4,7 @@ import { tmpdir } from 'os';import { join } from 'path';import { execFile } from 'child_process';import { promisify } from 'util';-import { spawnDetached, reapDetached, reapAndCleanDetachedDirs } from './detachedSpawn.js';+import { spawnDetached, reapDetached, reapAndCleanDetachedDirs, reattachDetached, isReattachable } from './detachedSpawn.js';const execFileAsync = promisify(execFile);const dirs = [];@@ -237,3 +237,98 @@ describe('spawnDetached', () => {});});});++describe('isReattachable', () => {+ it('is true while the recorded child is still alive', async () => {+ const controlDir = await tmpControlDir();+ const handle = await spawnDetached('sh', ['-c', 'sleep 30'], { controlDir, pollMs: 25 });+ expect(await isReattachable(controlDir)).toBe(true);+ handle.kill('SIGKILL');+ await onClose(handle);+ });++ it('is true after the child exited (RESULT line still unprocessed on disk)', async () => {+ const controlDir = await tmpControlDir();+ const handle = await spawnDetached('sh', ['-c', 'printf "x\\n"; exit 0'], { controlDir, pollMs: 25 });+ await onClose(handle);+ expect(await isReattachable(controlDir)).toBe(true);+ });++ it('is false when no pid was ever recorded', async () => {+ const controlDir = await tmpControlDir();+ expect(await isReattachable(controlDir)).toBe(false);+ });++ it('is false for a dead pid with no exit sentinel (killed mid-run)', async () => {+ const controlDir = await tmpControlDir();+ // A reparented-then-tree-killed orphan: pid recorded, never alive again,+ // and the supervisor never got to write `exit`. PID 2^31-1 is never live.+ await writeFile(join(controlDir, 'pid'), '2147483647');+ expect(await isReattachable(controlDir)).toBe(false);+ });+});++describe('reattachDetached', () => {+ it('replays a still-running survivor from the start and closes with its exit code', async () => {+ const controlDir = await tmpControlDir();+ // early output, then a beat, then late output + a non-zero exit.+ const original = await spawnDetached(+ 'sh', ['-c', 'printf "early\\n"; sleep 1; printf "late\\n"; exit 5'],+ { controlDir, pollMs: 25 }+ );+ // Attach the original's close listener NOW (before it can fire) — 'close' is+ // one-shot, so a listener added after the child exits would never resolve.+ const originalClosed = onClose(original);+ // Let "early" land on disk, then re-attach as if the server had restarted.+ await new Promise((r) => setTimeout(r, 150));+ const reattached = await reattachDetached(controlDir, { pollMs: 25 });+ expect(reattached).not.toBeNull();+ expect(reattached.pid).toBe(original.pid);+ const getOut = collect(reattached.stdout);+ const { code, signal } = await onClose(reattached);+ // The re-attached tailer reads from offset 0, so it sees the FULL output —+ // including bytes written before it attached — and the terminal exit code.+ expect(getOut()).toBe('early\nlate\n');+ expect(code).toBe(5);+ expect(signal).toBeNull();+ await originalClosed.catch(() => {});+ });++ it('recovers a job that FINISHED during the downtime (replays its result + close)', async () => {+ const controlDir = await tmpControlDir();+ const original = await spawnDetached('sh', ['-c', 'printf "RESULT:ok\\n"; exit 0'], { controlDir, pollMs: 25 });+ await onClose(original); // job already exited before we re-attach+ const reattached = await reattachDetached(controlDir, { pollMs: 25 });+ expect(reattached).not.toBeNull();+ const getOut = collect(reattached.stdout);+ const { code } = await onClose(reattached);+ expect(getOut()).toBe('RESULT:ok\n');+ expect(code).toBe(0);+ });++ it('returns null when there is no pid to attach to', async () => {+ const controlDir = await tmpControlDir();+ expect(await reattachDetached(controlDir, { pollMs: 25 })).toBeNull();+ });++ it('returns null for a dead pid with no exit sentinel', async () => {+ const controlDir = await tmpControlDir();+ await writeFile(join(controlDir, 'pid'), '2147483647');+ expect(await reattachDetached(controlDir, { pollMs: 25 })).toBeNull();+ });++ it('can SIGTERM the survivor through the re-attached handle', async () => {+ const controlDir = await tmpControlDir();+ const original = await spawnDetached('sh', ['-c', 'sleep 30'], { controlDir, pollMs: 25 });+ // Attach before the kill — the shared child's death closes BOTH handles, and+ // 'close' is one-shot, so the original's listener has to be wired up front.+ const originalClosed = onClose(original);+ await new Promise((r) => setTimeout(r, 100));+ const reattached = await reattachDetached(controlDir, { pollMs: 25 });+ const closed = onClose(reattached);+ expect(reattached.kill('SIGTERM')).toBe(true);+ const { signal } = await closed;+ expect(signal).toBe('SIGTERM');+ await originalClosed.catch(() => {});+ });+});diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.jsindex 1974d42b5b..26d624f9ab 100644--- a/server/services/loraTraining/index.js+++ b/server/services/loraTraining/index.js@@ -23,7 +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, reapDetached } from '../../lib/detachedSpawn.js';+import { spawnDetached, reapDetached, reattachDetached, isReattachable } from '../../lib/detachedSpawn.js';import { getImageModels } from '../../lib/mediaModels.js';import { resolveFlux2Python, isFlux2VenvHealthy } from '../../lib/pythonSetup.js';import { getSettings } from '../settings.js';@@ -324,6 +324,15 @@ export async function resumeTrainingRun(runId, { auto = false } = {}) {const emitFailed = (jobId, error) => trainingEvents.emit('failed', { generationId: jobId, error });+// Collapse checkpoint records to one per `step`, preserving first-seen order+// (last value wins for a given step). Keeps run.artifacts.checkpoints unique+// when a #1332 re-attach replays already-persisted checkpoint lines.+const dedupeCheckpointsByStep = (checkpoints) => {+ const byStep = new Map();+ for (const c of checkpoints) byStep.set(c?.step, c);+ return [...byStep.values()];+};+const flipDatasetAfterRun = (run, { trained, loraFilename = null }) => {const datasetId = run?.datasetId;if (!datasetId) return Promise.resolve();@@ -391,7 +400,7 @@ export const clearDatasetForDeletedLora = (run, deletedFilename) => {* queue's dispatcher; this function resolves once the child is spawned* (the queue awaits the terminal event separately).*/-export async function runTraining({ jobId, runId, pythonPath = null, resumeCheckpoint = null }) {+export async function runTraining({ jobId, runId, pythonPath = null, resumeCheckpoint = null, reattach = false }) {const fail = (message) => {console.error(`❌ training [${shortId(jobId)}] ${message}`);emitFailed(jobId, message);@@ -400,6 +409,7 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheckconst run = await runsDb.getRun(runId);if (!run) return fail(`run record missing: ${runId}`);const settings = await getSettings();+ const dir = runDir(runId);// Terminal failure BEFORE the child spawns: flip the run record to failed// AND release the dataset's `training` status, then emit the failed event.@@ -414,6 +424,27 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheckreturn fail(message);};+ // Boot re-attach (#1332): the queue re-enqueues a run whose detached trainer+ // SURVIVED a hard server restart with `reattach: true`. The child reparented+ // to init and is still training (or finished during the downtime), so we tail+ // its existing control-dir output instead of spawning a second trainer — no+ // staging, no validation, no fresh spawn. wireProcLifecycle then drives the+ // exact same line-handling/finalize path as a normal spawn, so a run that+ // completed mid-restart still registers its LoRA instead of being discarded.+ if (reattach) {+ const proc = await reattachDetached(join(dir, '.detached'));+ if (!proc) {+ // The survivor died (killed mid-run) with no RESULT to recover — fail the+ // run; its latest checkpoint stays resumable manually/auto, same as the+ // pre-#1332 reap path would have left it.+ return failBeforeSpawn('Trainer did not survive the restart — marking failed; resume from the latest checkpoint.');+ }+ console.log(`🔁 training [${shortId(jobId)}] re-attached to surviving trainer pid ${proc.pid} (run ${shortId(runId)})`);+ trainingEvents.emit('status', { generationId: jobId, message: 'Re-attached to trainer that survived a restart' });+ wireProcLifecycle(proc);+ return;+ }+// Re-validate — the dataset may have been edited/deleted while queued.let manifest;let dataset;@@ -450,7 +481,6 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheckreturn failBeforeSpawn(`Not enough free memory to train safely — ${memReport.budgetGb.toFixed(1)} GB available, need ≥ ${TRAINING_MIN_HEADROOM_GB} GB. Stop other model servers or close apps and retry.`);}- const dir = runDir(runId);const checkpointsDir = join(dir, 'checkpoints');const samplesDir = join(dir, 'samples');@@ -567,6 +597,15 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheck// `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') });+ wireProcLifecycle(proc);++ // Wire a freshly-spawned OR re-attached (#1332) trainer handle into the full+ // run lifecycle: live output streaming + progress mirror, the phase-aware+ // stall watchdog, and the close→finalize path that registers the LoRA. A+ // hoisted nested function so the early reattach branch (above) can call it too+ // — both paths share identical handling. Closes over jobId/runId/run/dir/+ // settings/fail/failBeforeSpawn.+ function wireProcLifecycle(proc) {activeProcess = proc;activeJobId = jobId;@@ -598,8 +637,13 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheckprogress: { ...current.progress, ...flushing.progress },artifacts: {...current.artifacts,- ...(flushing.checkpoints ? { checkpoints: [...current.artifacts.checkpoints, ...flushing.checkpoints] } : {}),- ...(flushing.samples ? { samples: [...current.artifacts.samples, ...flushing.samples] } : {}),+ // Dedupe on merge: a #1332 re-attach replays the survivor's whole log+ // from offset 0, re-firing onCheckpoint/onSample for artifacts already+ // persisted before the restart. Key checkpoints by step and samples by+ // filename (both unique) so a replay can't double-list them — last write+ // wins, which is identical for a true replay.+ ...(flushing.checkpoints ? { checkpoints: dedupeCheckpointsByStep([...current.artifacts.checkpoints, ...flushing.checkpoints]) } : {}),+ ...(flushing.samples ? { samples: [...new Set([...current.artifacts.samples, ...flushing.samples])] } : {}),},})).catch((err) => console.error(`❌ training [${shortId(jobId)}] progress persist failed: ${err?.message}`));};@@ -733,6 +777,7 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheckfail(`finalize failed: ${err?.message}`);});});+ } // end wireProcLifecycle}/**@@ -1027,6 +1072,22 @@ async function ensureCheckpointPreview(run, step, loraFilename) {console.log(`🖼️ training [${shortId(runId)}] preview attached for step ${step}`);}+/**+ * Boot probe used by the media-job queue's reconcile (#1332): does run `runId`+ * have a detached trainer worth re-attaching to (still alive, or finished but+ * its RESULT line never consumed) under its control dir? Lets the queue decide,+ * for a training job that was `running` at restart, whether to re-enqueue it for+ * re-attach or fail it — without the queue needing to know the run's on-disk+ * layout. Resolves false (never throws) when there's nothing to re-attach to.+ *+ * @param {string} runId+ * @returns {Promise<boolean>}+ */+export function hasSurvivingTrainer(runId) {+ if (!runId) return Promise.resolve(false);+ return isReattachable(join(runDir(runId), '.detached')).catch(() => false);+}+/*** Boot reconcile + terminal-state mirror. Called from server/index.js after* initMediaJobQueue(). Any run persisted as queued/running whose job isn't@@ -1034,6 +1095,11 @@ async function ensureCheckpointPreview(run, step, loraFilename) {* interrupted jobs — this keeps the two stores agreeing). Also subscribes* to mediaJobEvents so a queue-side cancel (user hits cancel while QUEUED,* which never reaches runTraining) still lands in the run record.+ *+ * A run whose detached trainer SURVIVED the restart is already re-enqueued for+ * re-attach by initMediaJobQueue (#1332) — its job is back in the queue as+ * queued/running, so the `!job || terminal` guard below skips it and the reap+ * path only touches runs that genuinely died.*/export async function initLoraTraining() {const active = await runsDb.listActiveRuns().catch((err) => {diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex 990cf465c1..4f26ffaec6 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -121,6 +121,17 @@ function getGenModuleForJob(job) {return Promise.resolve(null);}+// #1332: probe (via loraTraining, which owns the run's on-disk layout) whether+// a training run's detached trainer survived the restart and is worth+// re-attaching to. Lazy import avoids a static cycle (loraTraining statically+// imports this module). Never throws — a missing module / probe error reads as+// "not reattachable" so the reconcile falls back to the fail path.+async function jobHasSurvivingTrainer(runId) {+ const mod = await import('../loraTraining/index.js').catch(() => null);+ if (!mod?.hasSurvivingTrainer) return false;+ return mod.hasSurvivingTrainer(runId).catch(() => false);+}+// Drop the params snapshot of pythonPath; live settings always win for// local-Python jobs so a stale persisted snapshot can't poison the spawn.// Future live-resolved fields (e.g. model.runtime-aware overrides) belong@@ -258,19 +269,39 @@ export async function initMediaJobQueue() {const data = await readJSONFile(JOBS_FILE, { jobs: [] });const persistedJobs = Array.isArray(data?.jobs) ? data.jobs : [];const restartedFailedIds = [];+ // #1332: training jobs whose detached trainer survived the restart, to be+ // re-enqueued (flagged for re-attach) at the FRONT of the queue so they+ // resume before any new GPU work — collected during the reconcile, unshifted+ // after it (so the position recompute below sees them).+ const reattachJobs = [];// Video renders spawn a detached child that survives a pm2 restart, so an// interrupted render may still be alive and holding the GPU. Reap every// orphan under data/videos/.detached (and clean the scratch dirs) BEFORE// freeing lanes below — a job-id keyed reap would miss chained renders,// whose live child lives under a random inner chunk id, not the outer queue- // job id. (Training children are reaped in initLoraTraining, which knows- // each run's dir.) This runs before the worker starts, so every dir present- // is an orphan from the prior process.+ // job id. (Training children are handled per-job below: a survivor is+ // re-attached (#1332), and only a genuinely-dead one is reaped+failed in+ // initLoraTraining.) This runs before the worker starts, so every dir+ // present is an orphan from the prior process.const videoReap = await reapAndCleanDetachedDirs(join(PATHS.videos, '.detached')).catch(() => ({ reaped: 0 }));if (videoReap.reaped) console.log(`🧹 reaped ${videoReap.reaped} surviving render(s) on boot`);for (const j of persistedJobs) {if (j.status === 'running') {+ // #1332: a LoRA trainer is a detached child (spawnDetached) that can+ // SURVIVE this restart. If its run still has a live (or just-finished-+ // but-unprocessed) trainer, re-enqueue the SAME job flagged for+ // re-attach instead of failing it — runTraining({reattach:true}) tails+ // the survivor's output and finalizes it, so a run that completed during+ // the downtime still registers its LoRA. The probe lives in loraTraining+ // (it owns the run's on-disk layout); lazy-imported to avoid a static+ // cycle. Falls through to the fail path when nothing survived.+ // eslint-disable-next-line no-await-in-loop+ if (j.kind === 'training' && j.params?.runId && await jobHasSurvivingTrainer(j.params.runId)) {+ reattachJobs.push({ ...j, status: 'queued', params: { ...j.params, reattach: true } });+ console.log(`🔁 media-job [${j.id.slice(0, 8)}] training survived restart — re-enqueued for re-attach`);+ continue;+ }const failed = {...j,status: 'failed',@@ -296,6 +327,10 @@ export async function initMediaJobQueue() {archive.push(j);}}+ // Re-attach jobs resume ahead of everything else (they were mid-flight), so+ // unshift them to the front. At most one (single GPU lane), but spread keeps+ // their relative order if that ever changes.+ if (reattachJobs.length) queue.unshift(...reattachJobs);// The persisted `position` reflects the previous process' queue layout// (which may have included a now-failed running job). Recompute against// the current queue so /api/media-jobs and the initial SSE `queued`diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.jsindex 45fdd0760f..9087277da1 100644--- a/server/services/mediaJobQueue/index.test.js+++ b/server/services/mediaJobQueue/index.test.js@@ -45,6 +45,11 @@ tryReadFile: vi.fn().mockResolvedValue(null), jobId: 'whatever' })),cancelVideo: vi.fn(),cancelImage: vi.fn(),cancelImageCodex: vi.fn(),+ // #1332: loraTraining is dynamically imported by the queue for runTraining+ // (worker) and hasSurvivingTrainer (boot reconcile). Stub both so the boot+ // re-attach decision is testable without loading the real trainer module.+ runTraining: vi.fn(() => new Promise(() => {})),+ hasSurvivingTrainer: vi.fn(async () => false),};vi.mock('../videoGen/local.js', () => ({@@ -63,6 +68,12 @@ vi.mock('../imageGen/codex.js', () => ({cancel: (...args) => stubs.cancelImageCodex(...args),}));+vi.mock('../loraTraining/index.js', () => ({+ runTraining: (...args) => stubs.runTraining(...args),+ hasSurvivingTrainer: (...args) => stubs.hasSurvivingTrainer(...args),+ cancel: () => {},+}));+// Import the queue + the gen-event emitters AFTER the mocks above are// registered. Static imports would race with vi.mock hoisting on a real// dependency cycle, so dynamic-import this in beforeEach.@@ -85,6 +96,11 @@ beforeEach(async () => {// Default codex stub: hang (matches video/local defaults so tests that// don't care about codex don't accidentally complete too fast).stubs.generateImageCodex.mockImplementation(() => new Promise(() => {}));+ // #1332 training stubs lose their implementations on mockReset above; restore+ // safe defaults (no survivor; runTraining hangs so a re-attached run stays+ // 'running'). Individual tests override hasSurvivingTrainer as needed.+ stubs.runTraining.mockImplementation(() => new Promise(() => {}));+ stubs.hasSurvivingTrainer.mockResolvedValue(false);await importFresh();});@@ -444,6 +460,59 @@ describe('mediaJobQueue', () => {expect(recovered.error).toMatch(/interrupted by restart/);});+ it('boot recovery (#1332): a "running" training job whose trainer survived is re-enqueued for re-attach', async () => {+ const runId = 'run-survivor-1';+ const trainingId = '00000000-0000-4000-8000-000000000010';+ const persisted = {+ jobs: [{+ id: trainingId, kind: 'training', status: 'running',+ queuedAt: '2026-04-30T10:00:00.000Z', startedAt: '2026-04-30T10:00:01.000Z',+ params: { runId },+ }],+ };+ writeFileSync(join(tempDataDir, 'media-jobs.json'), JSON.stringify(persisted, null, 2));++ await importFresh();+ stubs.hasSurvivingTrainer.mockResolvedValue(true); // trainer is still alive+ await mediaJobQueue.initMediaJobQueue();++ // The reconcile consulted the probe with the run id.+ expect(stubs.hasSurvivingTrainer).toHaveBeenCalledWith(runId);+ // The worker resumes it via runTraining flagged reattach:true (NOT failed) —+ // the same job id so SSE clients keyed off it still resolve.+ await waitFor(() => stubs.runTraining.mock.calls.length === 1);+ expect(stubs.runTraining).toHaveBeenCalledWith(expect.objectContaining({+ jobId: trainingId, runId, reattach: true,+ }));+ // It occupies the GPU lane as a running job rather than being archived failed.+ const job = mediaJobQueue.getJob(trainingId);+ expect(job.status).toBe('running');+ expect(job.error).toBeUndefined();+ });++ it('boot recovery (#1332): a "running" training job with no surviving trainer is failed as before', async () => {+ const runId = 'run-dead-1';+ const trainingId = '00000000-0000-4000-8000-000000000011';+ const persisted = {+ jobs: [{+ id: trainingId, kind: 'training', status: 'running',+ queuedAt: '2026-04-30T10:00:00.000Z', startedAt: '2026-04-30T10:00:01.000Z',+ params: { runId },+ }],+ };+ writeFileSync(join(tempDataDir, 'media-jobs.json'), JSON.stringify(persisted, null, 2));++ await importFresh();+ stubs.hasSurvivingTrainer.mockResolvedValue(false); // trainer did not survive+ await mediaJobQueue.initMediaJobQueue();++ expect(stubs.hasSurvivingTrainer).toHaveBeenCalledWith(runId);+ const job = mediaJobQueue.getJob(trainingId);+ expect(job.status).toBe('failed');+ expect(job.error).toMatch(/interrupted by restart/);+ expect(stubs.runTraining).not.toHaveBeenCalled();+ });+it('boot recovery: persisted "queued" jobs are re-enqueued for the worker', async () => {const queuedId = '00000000-0000-4000-8000-000000000002';const persisted = {