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 (claude): warm stall detector fresh on re-attach instead of arming on replayed history; document PID-reuse bound (#1332)

Adam Eivya400d50e4d04
diff --git a/server/lib/detachedSpawn.js b/server/lib/detachedSpawn.js
index 32750971f3..5d7a6b26d5 100644
--- a/server/lib/detachedSpawn.js
+++ b/server/lib/detachedSpawn.js
@@ -174,9 +174,16 @@ function createLogTailer(handle, { controlDir, pollMs, cleanup }) {
// 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.
+ let replayedEmitted = false;
const tick = async () => {
if (closed) return;
await drainBoth();
+ // After the first drain, the entire pre-existing backlog has been emitted —
+ // for a fresh spawn that's ~nothing, but for a reattach (#1332) it's the
+ // whole replayed-from-offset-0 history. Fire a one-time 'replayed' so a
+ // consumer can tell replayed history from live output (e.g. to keep a
+ // wall-clock stall detector from arming on instantly-replayed step lines).
+ if (!replayedEmitted) { replayedEmitted = true; handle.emit('replayed'); }
const exited = await stat(exitFile).then((s) => s.size > 0).catch(() => false);
if (exited) {
await finish();
@@ -376,6 +383,14 @@ export async function isReattachable(controlDir) {
* `cleanup` default is false: a re-attached run's logs are its only post-mortem
* record, same as the original spawn.
*
+ * PID trust: like reapDetached/cancel, this trusts the persisted PID. In the
+ * vanishingly-unlikely case the OS recycled it onto an unrelated live process
+ * before boot, isAlive() reports true and we'd tail for an exit that never
+ * comes — but the caller (the training queue) wraps the re-attached run in its
+ * flat idle watchdog (WATCHDOG_TRAINING_MS), which fails the run and frees the
+ * GPU lane once no trainer output arrives, so a stale PID can't wedge the lane
+ * indefinitely. Matches the single-user trust model documented on reapDetached.
+ *
* @param {string} controlDir - the job's spawnDetached control dir
* @param {object} [opts]
* @param {number} [opts.pollMs] - tail/poll cadence (default 250ms)
diff --git a/server/lib/detachedSpawn.test.js b/server/lib/detachedSpawn.test.js
index 20f466f413..5a114b97e8 100644
--- a/server/lib/detachedSpawn.test.js
+++ b/server/lib/detachedSpawn.test.js
@@ -306,6 +306,30 @@ describe('reattachDetached', () => {
expect(code).toBe(0);
});
+ it('emits a one-time "replayed" signal once the initial backlog is drained', async () => {
+ const controlDir = await tmpControlDir();
+ const original = await spawnDetached(
+ 'sh', ['-c', 'printf "h1\\nh2\\n"; sleep 1; printf "live\\n"; exit 0'],
+ { controlDir, pollMs: 25 }
+ );
+ const originalClosed = onClose(original);
+ await new Promise((r) => setTimeout(r, 200)); // let the backlog (h1/h2) land
+ const reattached = await reattachDetached(controlDir, { pollMs: 25 });
+ const getOut = collect(reattached.stdout);
+ let replayedCount = 0;
+ let outAtReplayed = null;
+ reattached.on('replayed', () => { replayedCount += 1; outAtReplayed = getOut(); });
+ const { code } = await onClose(reattached);
+ // 'replayed' fires exactly once, AFTER the pre-existing backlog was emitted
+ // but BEFORE the post-restart "live" line — that's the boundary the stall
+ // detector uses to avoid arming on instantly-replayed step history.
+ expect(replayedCount).toBe(1);
+ expect(outAtReplayed).toBe('h1\nh2\n');
+ expect(getOut()).toBe('h1\nh2\nlive\n');
+ expect(code).toBe(0);
+ await originalClosed.catch(() => {});
+ });
+
it('returns null when there is no pid to attach to', async () => {
const controlDir = await tmpControlDir();
expect(await reattachDetached(controlDir, { pollMs: 25 })).toBeNull();
diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.js
index 26d624f9ab..6de74a332d 100644
--- a/server/services/loraTraining/index.js
+++ b/server/services/loraTraining/index.js
@@ -441,7 +441,7 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheck
}
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);
+ wireProcLifecycle(proc, { isReattach: true });
return;
}
@@ -605,7 +605,7 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheck
// 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) {
+ function wireProcLifecycle(proc, { isReattach = false } = {}) {
activeProcess = proc;
activeJobId = jobId;
@@ -691,6 +691,16 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheck
let stallKilled = false; // set when the tick SIGKILLs — close handler reads it
let stallTimer = null;
const stopStallWatchdog = () => { if (stallTimer) { clearInterval(stallTimer); stallTimer = null; } };
+ // The stall detector derives its budget from WALL-CLOCK gaps between STEP
+ // lines. On a #1332 re-attach the survivor's whole log is replayed from
+ // offset 0 in a few ms, so feeding those historical steps would record
+ // ~0ms intervals and instantly exit the 20-min warmup into the tight floor —
+ // false-killing a healthy slow-step run on its next live step. So on a
+ // re-attach we withhold step observation until the tailer's one-time
+ // 'replayed' signal (initial backlog drained); the detector then warms up
+ // fresh on genuinely-live output, exactly as a fresh spawn would.
+ let stallObserveLive = !isReattach;
+ if (isReattach) proc.on('replayed', () => { stallObserveLive = true; });
const makeSplitter = (stream) => {
let buf = '';
@@ -699,7 +709,7 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheck
// uncaught throw here would crash the server process.
try {
handleLine(text, stream);
- if (stallWatchdogOn) stallDetector.observe(text);
+ if (stallWatchdogOn && stallObserveLive) stallDetector.observe(text);
} catch (err) {
console.error(`❌ training [${shortId(jobId)}] line handler failed: ${err?.message}`);
}