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

address review (codex): reap surviving detached jobs on boot/resume so an orphan can't collide or hog the GPU (#1319)

[._.]/ Adam Eivy744b4c6aa556
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 5cf1fab5be..d968fe40e9 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -60,7 +60,7 @@
## 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)
+- **[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)
- **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)
diff --git a/server/lib/detachedSpawn.js b/server/lib/detachedSpawn.js
index f2468063e6..24de75bdeb 100644
--- a/server/lib/detachedSpawn.js
+++ b/server/lib/detachedSpawn.js
@@ -57,6 +57,10 @@ const DEFAULT_POLL_MS = 250;
// 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;
+// How long reapDetached lets a SIGTERM'd orphan checkpoint+exit before
+// escalating to SIGKILL. Matches the in-session cancel escalation (8s) plus
+// slack for a final checkpoint write.
+const REAP_GRACE_MS = 12000;
// `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')
@@ -298,3 +302,43 @@ export async function spawnDetached(bin, args = [], { env, cwd, controlDir, poll
return handle;
}
+
+const isAlive = (pid) => {
+ try { process.kill(pid, 0); return true; } catch { return false; }
+};
+
+/**
+ * Reap a detached job that outlived the server (boot recovery). Because
+ * spawnDetached children reparent to init, a `pm2 restart` leaves them running
+ * with no in-process handle — and the boot reconcile then marks their run/job
+ * failed. If such an orphan is still alive it must be stopped before that run
+ * is marked resumable (else a resume spawns a SECOND trainer into the same
+ * checkpoint dir) and before the GPU lane is freed (else a new job contends
+ * 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.)
+ *
+ * @param {string} controlDir - the job's spawnDetached control dir
+ * @returns {Promise<{reaped: boolean, pid?: number}>}
+ */
+export async function reapDetached(controlDir, { graceMs = REAP_GRACE_MS, pollMs = DEFAULT_POLL_MS } = {}) {
+ const pidRaw = await readFile(join(controlDir, 'pid'), 'utf8').catch(() => '');
+ const pid = Number.parseInt(pidRaw, 10);
+ if (!Number.isFinite(pid) || pid <= 0) return { reaped: false };
+ // Supervisor already recorded an exit → the job finished; nothing to reap.
+ const exitRaw = await readFile(join(controlDir, 'exit'), 'utf8').catch(() => '');
+ if (exitRaw.length > 0) return { reaped: false };
+ // Note: trusts the persisted PID. A reused PID (the job exited without the
+ // supervisor recording it AND the OS recycled the number within the few
+ // seconds before boot) is vanishingly unlikely on a single-user box; the same
+ // trust the in-session cancel path places in the child PID.
+ if (!isAlive(pid)) return { reaped: false };
+ try { process.kill(pid, 'SIGTERM'); } catch { return { reaped: false }; }
+ for (let waited = 0; waited < graceMs; waited += pollMs) {
+ await sleep(pollMs);
+ if (!isAlive(pid)) return { reaped: true, pid };
+ }
+ try { process.kill(pid, 'SIGKILL'); } catch { /* already gone */ }
+ return { reaped: true, pid };
+}
diff --git a/server/lib/detachedSpawn.test.js b/server/lib/detachedSpawn.test.js
index 5508286244..8dfc34033e 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 } from './detachedSpawn.js';
+import { spawnDetached, reapDetached } from './detachedSpawn.js';
const execFileAsync = promisify(execFile);
const dirs = [];
@@ -174,4 +174,41 @@ describe('spawnDetached', () => {
Object.defineProperty(process, 'platform', { value: original, configurable: true });
}
});
+
+ describe('reapDetached', () => {
+ const aliveByPs = async (pid) => {
+ const { stdout } = await execFileAsync('ps', ['-o', 'pid=', '-p', String(pid)]).catch(() => ({ stdout: '' }));
+ return stdout.trim().length > 0;
+ };
+
+ it('SIGTERMs a surviving orphan and reports it reaped', async () => {
+ const controlDir = await tmpControlDir();
+ const handle = await spawnDetached('sh', ['-c', 'sleep 30'], { controlDir, pollMs: 25 });
+ const pid = handle.pid;
+ expect(pid).toBeGreaterThan(0);
+ // Attach the close listener BEFORE reaping — the killed sleeper writes
+ // exit and the handle's own tail loop can fire 'close' before reap returns.
+ const closed = onClose(handle);
+ await new Promise((r) => setTimeout(r, 50));
+ const res = await reapDetached(controlDir, { graceMs: 3000, pollMs: 25 });
+ expect(res.reaped).toBe(true);
+ expect(res.pid).toBe(pid);
+ expect(await aliveByPs(pid)).toBe(false);
+ await closed;
+ });
+
+ it('is a no-op when the job already recorded an exit', async () => {
+ const controlDir = await tmpControlDir();
+ const handle = await spawnDetached('sh', ['-c', 'exit 0'], { controlDir, pollMs: 25 });
+ await onClose(handle);
+ const res = await reapDetached(controlDir, { graceMs: 200, pollMs: 25 });
+ expect(res.reaped).toBe(false);
+ });
+
+ it('is a no-op when no pid was ever recorded', async () => {
+ const controlDir = await tmpControlDir();
+ const res = await reapDetached(controlDir, { graceMs: 200, pollMs: 25 });
+ expect(res.reaped).toBe(false);
+ });
+ });
});
diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.js
index 887e2b78b4..bc5c3eaaf9 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 } from '../../lib/detachedSpawn.js';
+import { spawnDetached, reapDetached } from '../../lib/detachedSpawn.js';
import { getImageModels } from '../../lib/mediaModels.js';
import { resolveFlux2Python, isFlux2VenvHealthy } from '../../lib/pythonSetup.js';
import { getSettings } from '../settings.js';
@@ -221,6 +221,13 @@ export async function resumeTrainingRun(runId) {
status: 409, code: 'RUN_NOT_RESUMABLE',
});
}
+ // A run can be marked failed (boot reconcile / cancel) while its detached
+ // trainer is still alive — reap it before resuming so we never run two
+ // trainers against the same checkpoint dir. Idempotent: a no-op when nothing
+ // survives. Belt-and-suspenders with the boot-reconcile reap, since resume
+ // can race the reconcile's SIGTERM grace window.
+ const reaped = await reapDetached(join(runDir(runId), '.detached')).catch(() => ({ reaped: false }));
+ if (reaped.reaped) console.log(`🧹 reaped surviving trainer pid ${reaped.pid} before resuming run ${shortId(runId)}`);
// Both runtimes restore optimizer state + the step counter on resume, so
// training picks up mid-run and finishes at the original total: mflux via
// `mflux-train --resume <zip>`, and the torch FLUX.2 trainer via
@@ -944,6 +951,12 @@ export async function initLoraTraining() {
for (const run of active) {
const job = run.jobId ? getJob(run.jobId) : null;
if (!job || ['failed', 'canceled', 'completed'].includes(job.status)) {
+ // The trainer is a detached child that survives a pm2 restart, so it may
+ // STILL be running even though its in-memory job is gone. Reap it (clean
+ // SIGTERM → checkpoint → SIGKILL) before marking the run failed/resumable,
+ // so a resume can't spawn a second trainer into the same checkpoint dir.
+ const reaped = await reapDetached(join(runDir(run.id), '.detached')).catch(() => ({ reaped: false }));
+ if (reaped.reaped) console.log(`🧹 reaped surviving trainer pid ${reaped.pid} for run ${shortId(run.id)}`);
await runsDb.updateRun(run.id, {
status: 'failed', error: 'interrupted by restart', completedAt: new Date().toISOString(),
}).catch(() => {});
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index 712178070b..3d4361d73c 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -33,6 +33,7 @@ import { randomUUID } from 'crypto';
import { unlink } from 'fs/promises';
import { join, resolve as pathResolve, sep as PATH_SEP } from 'path';
import { PATHS, readJSONFile, atomicWrite, ensureDir, sleep } from '../../lib/fileUtils.js';
+import { reapDetached } from '../../lib/detachedSpawn.js';
import {
broadcastSse,
attachSseClient as attachSse,
@@ -259,6 +260,16 @@ export async function initMediaJobQueue() {
const restartedFailedIds = [];
for (const j of persistedJobs) {
if (j.status === 'running') {
+ // Video renders spawn a detached child that survives a pm2 restart, so
+ // the persisted 'running' job may still be alive. Reap it (SIGTERM →
+ // SIGKILL) before freeing the lane, else the orphan keeps consuming the
+ // GPU while a newly-dequeued job runs concurrently. (Training children
+ // are reaped in initLoraTraining, which knows their run dir.)
+ if (j.kind === 'video') {
+ // eslint-disable-next-line no-await-in-loop
+ const reaped = await reapDetached(join(PATHS.videos, '.detached', j.id)).catch(() => ({ reaped: false }));
+ if (reaped.reaped) console.log(`🧹 reaped surviving render pid ${reaped.pid} for job ${j.id.slice(0, 8)}`);
+ }
const failed = {
...j,
status: 'failed',