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

feat: phase-aware stall watchdog for LoRA training with checkpoint auto-resume (#1330)

Adam Eivy7e55331a6045
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9619e6a092..11f107b3ce 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **[issue-1330] Phase-aware stall watchdog catches a wedged GPU mid-training and auto-resumes from the newest checkpoint.** The training job queue's idle watchdog only trips on *total* silence (no runner output for 30 minutes) — but a *soft* GPU hang during mflux/FLUX.2 training is invisible to it, because the trainer's heartbeat and telemetry threads keep emitting lines while the step loop is wedged, perpetually resetting the flat timer. PortOS now runs a **phase-aware** stall detector that keys off the trainer's `STAGE:`/`STEP:` line protocol: once steps are flowing it derives a per-step budget from the *observed* step rate (a few × the slowest recent interval, floored and capped below the flat watchdog) and enforces it **only during `STAGE:training`** — model-load, dataset-encode, mid-training sampling, and inter-segment cooldown stay on the generous flat watchdog so a legitimately slow phase is never false-killed. When training genuinely stalls, the wedged child is **SIGKILLed immediately** (SIGTERM relies on the GIL the hang holds) and the run **auto-resumes from its newest checkpoint** via the existing resume path — bounded to a couple of attempts per run so a config that wedges every segment can't resume-loop forever, after which the run stays failed for manual resume. This recovers *soft* hangs faster; it does **not** address the hard-reboot kernel panics (checkpoint-resume already covers those, since the machine is gone before any userspace watchdog runs). Off-switch: `settings.loraTraining.stallWatchdog = false`. (`server/services/loraTraining/stallDetector.js`, `server/services/loraTraining/index.js`, `server/lib/validation.js`) (#1330)
+
- **[issue-1335] Import can clean up paste/PDF formatting with AI as it brings a manuscript in.** Text imported from a PDF or paste arrives mangled — hard-wrapped lines, split drop-caps, hyphenated wraps, orphaned quotes — and until now every imported issue needed a manual Reformat pass in the editor afterward. The import Review panel gains an optional **Clean up formatting with AI** checkbox (off by default): when ticked, each issue's excerpt is run through the same word-preserving reformat pass the editor's Reformat button uses, so manuscripts (and comic scripts / screenplays) land already-clean. It's best-effort — a reformat that fails or would change any wording silently keeps the original text, so an import never breaks — and a live per-issue checklist shows progress while it runs. Left off by default because it's one AI pass per issue, so a large import opts in deliberately. (#1335)
- **[issue-1325] Video renders now record the exact runtime they ran on — and you can see it at a glance.** Garbled or "mosaic" video output is often a per-chip/per-runtime numerical quirk rather than an outright crash, and until now a render left no trace of the stack that produced it. Each local video render now stamps a one-line **runtime fingerprint** — the resolved ltx/mlx (or torch+CUDA on Windows) versions plus your chip, OS, and Python — into the render log and onto the saved history record, so a problem render self-documents the environment that made it. The Video Gen status header also shows your host chip/OS and the installed runtimes' versions on demand, without running a render — so a bug report can carry the version info that makes it actionable. (#1325)
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 014f77daa2..ae03e574b5 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -856,6 +856,12 @@ export const loraTrainingConfigSchema = z.object({
// the GPU-driver hang. Cooldown is the GPU idle gap (seconds) between segments.
segmentation: z.boolean().optional(),
segmentCooldownSec: z.number().int().min(0).max(3600).optional(),
+ // Phase-aware soft-hang stall watchdog (issue #1330, default ON in
+ // services/loraTraining/index.js). Detects a wedged GPU mid-training (steps
+ // stop arriving within a step-rate-derived budget) and SIGKILLs + auto-resumes
+ // from the newest checkpoint. Set false to fall back to only the flat 30-min
+ // idle watchdog (e.g. if a future driver fix makes soft hangs impossible).
+ stallWatchdog: z.boolean().optional(),
});
// POST /api/lora-training/runs — start a training run for a dataset.
diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.js
index bc5c3eaaf9..1974d42b5b 100644
--- a/server/services/loraTraining/index.js
+++ b/server/services/loraTraining/index.js
@@ -40,6 +40,7 @@ import {
MFLUX_DEFAULT_COOLDOWN_SEC,
} from './runtimes.js';
import { makeTrainingLineHandler } from './progress.js';
+import { makeStallDetector } from './stallDetector.js';
import { prepareMemoryForTraining, TRAINING_MIN_HEADROOM_GB } from './memoryPrep.js';
import { classifyTrainingFailure } from './failure.js';
import { buildTrainedSidecar, trainedLoraFilename } from './sidecar.js';
@@ -79,6 +80,20 @@ export const isMfluxTrainAvailable = (pythonPath) =>
let activeProcess = null;
let activeJobId = null;
+// Phase-aware stall watchdog (issue #1330): how many times a single run may be
+// auto-resumed after a *soft* GPU hang before we give up and let it stay failed.
+// Bounded so a config that wedges every segment can't resume-loop forever — the
+// user sees a failed run after N attempts and intervenes. Counted separately
+// from manual resumes (run.resume.autoCount). Env-overridable.
+const STALL_MAX_AUTO_RESUMES = (() => {
+ const n = Number(process.env.LORA_TRAIN_STALL_MAX_AUTO_RESUMES);
+ return Number.isFinite(n) && n >= 0 ? n : 2;
+})();
+// How often the watchdog polls checkStall while a trainer is running. Well
+// under the 90s floor budget so a stall is caught within ~one tick of the
+// budget elapsing (worst-case detection lag = budget + one tick).
+const STALL_TICK_MS = 30_000;
+
export const cancel = (jobId) => {
if (!activeProcess || (jobId && activeJobId !== jobId)) return false;
const proc = activeProcess;
@@ -214,7 +229,7 @@ export async function startTrainingRun({ datasetId, baseModelId, name = null, pa
* usual. Progress may briefly read low if the trainer restarts its step bar at
* the resume point — cosmetic; the durable record catches up on the next flush.
*/
-export async function resumeTrainingRun(runId) {
+export async function resumeTrainingRun(runId, { auto = false } = {}) {
const run = await runsDb.getRunRequired(runId);
if (!['failed', 'canceled'].includes(run.status)) {
throw new ServerError(`Can only resume a failed or canceled run (status: ${run.status})`, {
@@ -293,13 +308,17 @@ export async function resumeTrainingRun(runId) {
completedAt: null,
resume: {
count: (current.resume?.count || 0) + 1,
+ // Auto (stall-watchdog) resumes are counted separately so the watchdog
+ // can cap its own retries without a manual resume resetting the budget.
+ autoCount: (current.resume?.autoCount || 0) + (auto ? 1 : 0),
fromStep: checkpoint.step,
resumedAt: new Date().toISOString(),
+ lastReason: auto ? 'stall-watchdog' : 'manual',
},
}));
await stampDatasetTrainingStatus(run, queued.jobId);
- console.log(`🏋️ Training run ${shortId(runId)} resumed from step ${checkpoint.step} — job=${shortId(queued.jobId)}`);
+ console.log(`🏋️ Training run ${shortId(runId)} ${auto ? 'auto-resumed (stall watchdog)' : 'resumed'} from step ${checkpoint.step} — job=${shortId(queued.jobId)}`);
return { runId, jobId: queued.jobId, position: queued.position, status: 'queued', fromStep: checkpoint.step };
}
@@ -614,12 +633,30 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheck
sampleUrl: (path) => `/api/lora-training/runs/${runId}/samples/${basename(path)}`,
});
+ // Phase-aware soft-hang stall watchdog (issue #1330). The queue's flat 30-min
+ // idle watchdog only trips on TOTAL silence and can't see a soft GPU hang
+ // mid-training (the python heartbeat/telemetry threads keep emitting lines, so
+ // the flat watchdog never fires). This detector keys off the STAGE/STEP
+ // protocol to apply a tight, step-rate-derived budget ONLY during
+ // STAGE:training — load/encode/sampling/cooldown stay on the flat watchdog so
+ // a legitimately slow phase is never false-killed. On a training-phase stall
+ // we SIGKILL the wedged child; the close handler auto-resumes from the newest
+ // checkpoint. Disable via settings.loraTraining.stallWatchdog = false.
+ const stallWatchdogOn = (settings?.loraTraining?.stallWatchdog !== false);
+ const stallDetector = makeStallDetector();
+ let stallKilled = false; // set when the tick SIGKILLs — close handler reads it
+ let stallTimer = null;
+ const stopStallWatchdog = () => { if (stallTimer) { clearInterval(stallTimer); stallTimer = null; } };
+
const makeSplitter = (stream) => {
let buf = '';
const safeLine = (text) => {
// try/catch: this runs inside a child-process data/end callback — an
// uncaught throw here would crash the server process.
- try { handleLine(text, stream); } catch (err) {
+ try {
+ handleLine(text, stream);
+ if (stallWatchdogOn) stallDetector.observe(text);
+ } catch (err) {
console.error(`❌ training [${shortId(jobId)}] line handler failed: ${err?.message}`);
}
};
@@ -646,7 +683,31 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheck
proc.stderr.on('data', stderrSplitter.push);
proc.stderr.on('end', stderrSplitter.flush);
+ if (stallWatchdogOn) {
+ stallTimer = setInterval(() => {
+ // setInterval callback — runs outside the request lifecycle, so guard
+ // against any throw (a crash here would take down the server process).
+ try {
+ if (stallKilled || activeProcess !== proc) return;
+ const { stalled, idleMs, budgetMs } = stallDetector.checkStall();
+ if (!stalled) return;
+ stallKilled = true;
+ stopStallWatchdog();
+ console.log(`⏱️ training [${shortId(jobId)}] phase-aware watchdog: training stalled ${Math.round(idleMs / 1000)}s (budget ${Math.round(budgetMs / 1000)}s) — SIGKILL + auto-resume`);
+ // Soft hang: SIGKILL straight away (SIGTERM relies on the GIL the hang
+ // holds, so the 8s escalation in cancel() would just waste the window).
+ // The newest checkpoint is the resume point; the close handler picks it
+ // up. Direct PID kill via the detached handle.
+ proc.kill('SIGKILL');
+ } catch (err) {
+ console.error(`❌ training [${shortId(jobId)}] stall watchdog tick failed: ${err?.message}`);
+ }
+ }, STALL_TICK_MS);
+ stallTimer.unref?.();
+ }
+
proc.on('error', (err) => {
+ stopStallWatchdog();
if (activeProcess === proc) { activeProcess = null; activeJobId = null; }
// A launch failure after the run was marked `running` — a genuine spawn
// error, or (with spawnDetached) the control dir failing to create/clear.
@@ -659,13 +720,14 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheck
});
proc.on('close', (code, signal) => {
+ stopStallWatchdog();
if (activeProcess === proc) { activeProcess = null; activeJobId = null; }
// Flush the debounced progress (final checkpoint + last sample) BEFORE
// finalize reads the run record — the collapse guard and previewImageUrl
// both read run.artifacts. Async finalize wrapped so a rejection can't
// escape the event handler (unhandled rejection kills the process on Node ≥15).
Promise.resolve(flushProgress())
- .then(() => finalizeTraining({ jobId, runId, code, signal, state: getState() }))
+ .then(() => finalizeTraining({ jobId, runId, code, signal, state: getState(), stallKilled }))
.catch((err) => {
console.error(`❌ training [${shortId(jobId)}] finalize failed: ${err?.message}`);
fail(`finalize failed: ${err?.message}`);
@@ -673,7 +735,31 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheck
});
}
-async function finalizeTraining({ jobId, runId, code, signal, state }) {
+/**
+ * After a phase-aware-watchdog SIGKILL, auto-resume the run from its newest
+ * checkpoint (issue #1330) — bounded by STALL_MAX_AUTO_RESUMES so a config that
+ * wedges every segment can't resume-loop forever. Best-effort: any failure
+ * leaves the run in its finalize-set `failed` state for manual resume. Runs
+ * outside the request lifecycle (called from the close handler), so it owns its
+ * own error handling rather than bubbling.
+ */
+async function autoResumeAfterStall(runId, jobId) {
+ const run = await runsDb.getRun(runId).catch(() => null);
+ if (!run) return;
+ const autoCount = run.resume?.autoCount || 0;
+ if (autoCount >= STALL_MAX_AUTO_RESUMES) {
+ console.log(`⚠️ training [${shortId(jobId)}] stall auto-resume budget exhausted (${autoCount}/${STALL_MAX_AUTO_RESUMES}) — leaving run failed for manual resume`);
+ return;
+ }
+ // resumeTrainingRun requires a failed/canceled status + a resumable checkpoint;
+ // finalize has already flipped the run to failed by the time this runs.
+ await resumeTrainingRun(runId, { auto: true }).then(
+ (res) => console.log(`🔁 training [${shortId(jobId)}] auto-resumed run ${shortId(runId)} from step ${res.fromStep} (attempt ${autoCount + 1}/${STALL_MAX_AUTO_RESUMES})`),
+ (err) => console.error(`❌ training [${shortId(jobId)}] stall auto-resume failed: ${err?.message} — run stays failed for manual resume`),
+ );
+}
+
+async function finalizeTraining({ jobId, runId, code, signal, state, stallKilled = false }) {
const run = await runsDb.getRun(runId);
const job = getJob(jobId);
const canceled = !!job?.cancelRequested;
@@ -765,6 +851,12 @@ async function finalizeTraining({ jobId, runId, code, signal, state }) {
await flipDatasetAfterRun(run, { trained: false });
console.error(`❌ training [${shortId(jobId)}] ${failCode}: ${message}`);
trainingEvents.emit('failed', { generationId: jobId, error: message, code: failCode, repo: failRepo });
+
+ // Phase-aware watchdog SIGKILL (issue #1330): the run is now `failed`, so
+ // resumeTrainingRun's status precondition is satisfied — auto-resume from the
+ // newest checkpoint. Bounded by STALL_MAX_AUTO_RESUMES; awaited so the resume
+ // (re-enqueue + run-record flip back to queued) completes within finalize.
+ if (stallKilled) await autoResumeAfterStall(runId, jobId);
}
/**
diff --git a/server/services/loraTraining/resume.test.js b/server/services/loraTraining/resume.test.js
index dd3bd45950..ea6ff88df8 100644
--- a/server/services/loraTraining/resume.test.js
+++ b/server/services/loraTraining/resume.test.js
@@ -94,4 +94,29 @@ describe('resumeTrainingRun — flux2 path', () => {
await expect(resumeTrainingRun('run-flux2')).rejects.toMatchObject({ code: 'RUN_NOT_RESUMABLE' });
expect(enqueueJobMock).not.toHaveBeenCalled();
});
+
+ // Issue #1330: the phase-aware stall watchdog auto-resumes with { auto: true }.
+ // The resume bookkeeping must increment autoCount (the watchdog's own budget,
+ // separate from total count) and stamp lastReason so the cap is enforceable.
+ it('stamps auto-resume bookkeeping (autoCount + lastReason) when auto:true', async () => {
+ getRunRequiredMock.mockResolvedValue(flux2Run({ resume: { count: 1, autoCount: 1 } }));
+ resolveLatestCheckpointArtifactMock.mockReturnValue({ step: 300, path: '/runs/run-flux2/checkpoints/step-000300' });
+
+ await resumeTrainingRun('run-flux2', { auto: true });
+
+ const updater = updateRunMock.mock.calls.find((c) => c[0] === 'run-flux2' && typeof c[1] === 'function')[1];
+ const next = updater(flux2Run({ resume: { count: 1, autoCount: 1 } }));
+ expect(next.resume).toMatchObject({ count: 2, autoCount: 2, fromStep: 300, lastReason: 'stall-watchdog' });
+ });
+
+ it('manual resume does not bump autoCount and stamps lastReason manual', async () => {
+ getRunRequiredMock.mockResolvedValue(flux2Run({ resume: { count: 2, autoCount: 2 } }));
+ resolveLatestCheckpointArtifactMock.mockReturnValue({ step: 300, path: '/runs/run-flux2/checkpoints/step-000300' });
+
+ await resumeTrainingRun('run-flux2');
+
+ const updater = updateRunMock.mock.calls.find((c) => c[0] === 'run-flux2' && typeof c[1] === 'function')[1];
+ const next = updater(flux2Run({ resume: { count: 2, autoCount: 2 } }));
+ expect(next.resume).toMatchObject({ count: 3, autoCount: 2, lastReason: 'manual' });
+ });
});
diff --git a/server/services/loraTraining/stallDetector.js b/server/services/loraTraining/stallDetector.js
new file mode 100644
index 0000000000..675e7d38ca
--- /dev/null
+++ b/server/services/loraTraining/stallDetector.js
@@ -0,0 +1,166 @@
+/**
+ * Phase-aware soft-hang stall detector for LoRA training.
+ *
+ * The mediaJobQueue idle watchdog (WATCHDOG_TRAINING_MS, flat 30 min) only
+ * trips on *total* silence — any non-noise line resets it. That's the right
+ * backstop for a wedged model-load or dataset-encode (which legitimately go
+ * silent for minutes), but it's blind to a soft GPU hang *during training*:
+ * once steps are flowing every few seconds, a 30-min gap between `STEP:` lines
+ * is clearly wedged long before the flat watchdog fires.
+ *
+ * This detector keys off the trainer line protocol (`STAGE:<name>`,
+ * `STEP:<cur>:<total>:<loss>` — same lines progress.js parses) to apply a
+ * *tight* budget only while `STAGE:training` is active: consecutive `STEP:`
+ * lines must arrive within a few × the observed per-step interval. Every other
+ * phase (load-model, precompute-latents, sampling, cooldown, or pre-first-step
+ * graph-compile) is left to the flat queue watchdog so a legitimately slow
+ * load/encode is never false-killed — the budget is *derived from the first few
+ * observed step intervals*, never a hardcoded per-step value.
+ *
+ * Pure factory, no I/O — the clock is injected so unit tests drive it with
+ * synthetic line streams. Caller (runTraining) feeds raw lines via observe()
+ * and polls checkStall(); a stalled training phase triggers SIGKILL +
+ * checkpoint-resume in the orchestrator.
+ *
+ * IMPORTANT: this recovers *soft* GPU hangs faster — it does NOT address the
+ * hard-reboot kernel panics (the machine is gone before any userspace watchdog
+ * runs; checkpoint-resume already covers those).
+ */
+
+// Env-overridable like mediaJobQueue's WATCHDOG_* knobs. `Number(non-numeric)`
+// → NaN; fall back to the default when the parsed value isn't positive-finite.
+const envMs = (value, defaultMs) => {
+ const n = Number(value);
+ return Number.isFinite(n) && n > 0 ? n : defaultMs;
+};
+const envNum = (value, defaultN) => {
+ const n = Number(value);
+ return Number.isFinite(n) && n > 0 ? n : defaultN;
+};
+
+// Budget = (slowest of the recent step intervals) × this. "A few ×" the
+// observed per-step time, so normal jitter (a GC pause, a checkpoint write
+// between steps) never trips it — only a genuine multi-step-long wedge does.
+export const STALL_STEP_MULTIPLIER = envNum(process.env.LORA_TRAIN_STALL_STEP_MULTIPLIER, 6);
+// Need at least this many consecutive intervals before the tight budget arms —
+// until then the generous warmup budget applies (first step compiles the Metal
+// graph and is pathologically slower than steady state).
+export const STALL_MIN_STEP_SAMPLES = envNum(process.env.LORA_TRAIN_STALL_MIN_SAMPLES, 3);
+// Floor: never kill faster than this even when steps are sub-second apart, so a
+// burst of fast early steps can't set a budget so tight that one slow step trips.
+export const STALL_MIN_BUDGET_MS = envMs(process.env.LORA_TRAIN_STALL_MIN_BUDGET_MS, 90_000);
+// Cap: kept below the flat WATCHDOG_TRAINING_MS (30 min) so the phase-aware
+// detector always fires first during training — even for slow steps.
+export const STALL_MAX_BUDGET_MS = envMs(process.env.LORA_TRAIN_STALL_MAX_BUDGET_MS, 15 * 60 * 1000);
+// Generous budget before the tight one arms (and for the gap between entering
+// STAGE:training and the first STEP — the graph compile). Defers to the flat
+// queue watchdog in practice; here only to bound a never-stepping training phase.
+export const STALL_WARMUP_BUDGET_MS = envMs(process.env.LORA_TRAIN_STALL_WARMUP_BUDGET_MS, 20 * 60 * 1000);
+
+// Same STAGE/STEP grammar progress.js uses. The `:heartbeat:<N>s` suffix is a
+// keep-alive that must NOT count as a phase change (it's emitted during a long
+// cooldown to feed the flat watchdog without altering the displayed stage).
+const STAGE_RE = /^STAGE:([a-zA-Z0-9_-]+)(?::heartbeat:(\d+)s)?/;
+const STEP_RE = /^STEP:(\d+):(\d+):/;
+
+/**
+ * @param {object} [opts]
+ * @param {() => number} [opts.now] injected clock (ms) — tests pass a stub.
+ * @returns {{ observe, checkStall, getPhase, getStepSamples }}
+ */
+export function makeStallDetector({
+ now = () => Date.now(),
+ stepMultiplier = STALL_STEP_MULTIPLIER,
+ minStepSamples = STALL_MIN_STEP_SAMPLES,
+ minBudgetMs = STALL_MIN_BUDGET_MS,
+ maxBudgetMs = STALL_MAX_BUDGET_MS,
+ warmupBudgetMs = STALL_WARMUP_BUDGET_MS,
+} = {}) {
+ let phase = null; // current non-heartbeat STAGE name
+ let trainingEnteredAt = null; // ms the current training segment began
+ let lastStepAt = null; // ms of the last STEP line in this segment
+ let lastStepNum = null; // dedupe tqdm redraws at the same step
+ const intervals = []; // gaps (ms) between consecutive STEP lines
+
+ // Each training segment is timed independently: a resume / post-sampling
+ // re-entry spawns a fresh compile, so prior step-rate data doesn't apply and
+ // the warmup window must restart. Conservative by design (re-enters warmup
+ // after every sampling/cooldown boundary) — zero false kills beats faster
+ // detection across a segment seam.
+ const resetTrainingTiming = () => {
+ trainingEnteredAt = null;
+ lastStepAt = null;
+ lastStepNum = null;
+ intervals.length = 0;
+ };
+
+ const enterTraining = (ts) => {
+ if (phase !== 'training') {
+ resetTrainingTiming();
+ trainingEnteredAt = ts;
+ }
+ phase = 'training';
+ };
+
+ const observe = (rawLine, ts = now()) => {
+ const line = String(rawLine).trim();
+ if (!line) return;
+
+ const stage = STAGE_RE.exec(line);
+ if (stage) {
+ if (stage[2]) return; // heartbeat keep-alive — not a phase transition
+ if (stage[1] === 'training') {
+ enterTraining(ts);
+ } else {
+ phase = stage[1];
+ resetTrainingTiming(); // leaving training disables tight enforcement
+ }
+ return;
+ }
+
+ const step = STEP_RE.exec(line);
+ if (step) {
+ const cur = Number(step[1]);
+ // A STEP implies training even if the STAGE:training line was missed or
+ // arrived out of order (stderr/stdout interleave).
+ enterTraining(ts);
+ if (lastStepAt != null && cur !== lastStepNum) {
+ intervals.push(ts - lastStepAt);
+ // Keep a bounded recent window — late-run steps may slow as memory
+ // pressure builds, so the budget should track the recent rate.
+ if (intervals.length > minStepSamples * 3) intervals.shift();
+ }
+ lastStepAt = ts;
+ lastStepNum = cur;
+ }
+ };
+
+ // Derived budget: slowest of the recent intervals × multiplier, clamped to
+ // [min, max]. Until enough samples, the generous warmup budget applies.
+ const currentBudgetMs = () => {
+ if (intervals.length < minStepSamples) return warmupBudgetMs;
+ const recent = intervals.slice(-minStepSamples * 2);
+ const slowest = Math.max(...recent);
+ return Math.min(maxBudgetMs, Math.max(minBudgetMs, slowest * stepMultiplier));
+ };
+
+ const checkStall = (ts = now()) => {
+ if (phase !== 'training') {
+ return { stalled: false, phase, idleMs: 0, budgetMs: 0, stepSamples: intervals.length };
+ }
+ const since = lastStepAt ?? trainingEnteredAt;
+ if (since == null) {
+ return { stalled: false, phase, idleMs: 0, budgetMs: 0, stepSamples: intervals.length };
+ }
+ const idleMs = ts - since;
+ const budgetMs = currentBudgetMs();
+ return { stalled: idleMs > budgetMs, phase, idleMs, budgetMs, stepSamples: intervals.length };
+ };
+
+ return {
+ observe,
+ checkStall,
+ getPhase: () => phase,
+ getStepSamples: () => intervals.length,
+ };
+}
diff --git a/server/services/loraTraining/stallDetector.test.js b/server/services/loraTraining/stallDetector.test.js
new file mode 100644
index 0000000000..a13bb30366
--- /dev/null
+++ b/server/services/loraTraining/stallDetector.test.js
@@ -0,0 +1,169 @@
+import { describe, it, expect } from 'vitest';
+import { makeStallDetector } from './stallDetector.js';
+
+// Drives the detector with a synthetic, injected clock so step intervals and
+// idle gaps are deterministic — no real time, no child process.
+function makeClock(start = 0) {
+ let t = start;
+ return {
+ now: () => t,
+ advance: (ms) => { t += ms; return t; },
+ set: (ms) => { t = ms; return t; },
+ };
+}
+
+describe('makeStallDetector', () => {
+ it('does not arm during model load / non-training phases', () => {
+ const clock = makeClock();
+ const d = makeStallDetector({ now: clock.now });
+ d.observe('STAGE:load-model');
+ clock.advance(60 * 60 * 1000); // an hour of silence loading a multi-GB model
+ expect(d.getPhase()).toBe('load-model');
+ expect(d.checkStall().stalled).toBe(false);
+ });
+
+ it('uses the generous warmup budget before enough step samples', () => {
+ const clock = makeClock();
+ const d = makeStallDetector({ now: clock.now, warmupBudgetMs: 20 * 60 * 1000 });
+ d.observe('STAGE:training');
+ d.observe('STEP:1:600:0.42'); // first step — graph compile, no interval yet
+ clock.advance(10 * 60 * 1000); // 10 min: slow, but under the warmup budget
+ expect(d.checkStall().stalled).toBe(false);
+ clock.advance(11 * 60 * 1000); // now 21 min since the step — past warmup
+ expect(d.checkStall().stalled).toBe(true);
+ });
+
+ it('arms a tight budget once step intervals are observed and trips on a wedge', () => {
+ const clock = makeClock();
+ const d = makeStallDetector({
+ now: clock.now,
+ minStepSamples: 3,
+ stepMultiplier: 6,
+ minBudgetMs: 90_000,
+ });
+ d.observe('STAGE:training', clock.now());
+ // Four steps, 10s apart → three observed 10s intervals (>= minStepSamples).
+ for (let i = 1; i <= 4; i += 1) {
+ d.observe(`STEP:${i}:600:0.4`, clock.now());
+ clock.advance(10_000);
+ }
+ expect(d.getStepSamples()).toBeGreaterThanOrEqual(3);
+ // Budget = max(90s floor, 10s × 6) = 90s. 80s idle is fine.
+ clock.advance(80_000);
+ expect(d.checkStall().stalled).toBe(false);
+ // 100s total idle exceeds the 90s floor budget.
+ clock.advance(20_000);
+ const res = d.checkStall();
+ expect(res.stalled).toBe(true);
+ expect(res.phase).toBe('training');
+ expect(res.budgetMs).toBe(90_000);
+ });
+
+ it('derives a larger budget from slower steps (multiplier above the floor)', () => {
+ const clock = makeClock();
+ const d = makeStallDetector({
+ now: clock.now,
+ minStepSamples: 3,
+ stepMultiplier: 6,
+ minBudgetMs: 90_000,
+ maxBudgetMs: 15 * 60 * 1000,
+ });
+ d.observe('STAGE:training', clock.now());
+ for (let i = 1; i <= 4; i += 1) {
+ d.observe(`STEP:${i}:600:0.4`, clock.now());
+ clock.advance(60_000); // 60s/step
+ }
+ // Budget = 60s × 6 = 360s (above the 90s floor, below the 15min cap).
+ expect(d.checkStall().budgetMs).toBe(360_000);
+ clock.advance(300_000); // 5 min idle — under 6 min budget
+ expect(d.checkStall().stalled).toBe(false);
+ clock.advance(70_000); // now 370s idle — over budget
+ expect(d.checkStall().stalled).toBe(true);
+ });
+
+ it('caps the budget so it always fires before the flat 30-min watchdog', () => {
+ const clock = makeClock();
+ const d = makeStallDetector({
+ now: clock.now,
+ minStepSamples: 3,
+ stepMultiplier: 6,
+ maxBudgetMs: 15 * 60 * 1000,
+ });
+ d.observe('STAGE:training', clock.now());
+ for (let i = 1; i <= 4; i += 1) {
+ d.observe(`STEP:${i}:600:0.4`, clock.now());
+ clock.advance(10 * 60 * 1000); // absurdly slow 10min/step → ×6 = 60min, capped to 15min
+ }
+ expect(d.checkStall().budgetMs).toBe(15 * 60 * 1000);
+ });
+
+ it('does not double-count tqdm redraws at the same step number', () => {
+ const clock = makeClock();
+ const d = makeStallDetector({ now: clock.now, minStepSamples: 3 });
+ d.observe('STAGE:training', clock.now());
+ d.observe('STEP:1:600:0.4', clock.now());
+ clock.advance(5_000);
+ d.observe('STEP:1:600:0.4', clock.now()); // same step redraw — no interval
+ clock.advance(5_000);
+ d.observe('STEP:1:600:0.4', clock.now());
+ expect(d.getStepSamples()).toBe(0); // never advanced past step 1
+ });
+
+ it('treats heartbeat keep-alives as activity, not a phase change', () => {
+ const clock = makeClock();
+ const d = makeStallDetector({ now: clock.now });
+ d.observe('STAGE:training', clock.now());
+ d.observe('STAGE:training:heartbeat:30s', clock.now());
+ expect(d.getPhase()).toBe('training');
+ // A cooldown-phase heartbeat must not re-arm training enforcement.
+ d.observe('STAGE:cooldown', clock.now());
+ d.observe('STAGE:cooldown:heartbeat:30s', clock.now());
+ expect(d.getPhase()).toBe('cooldown');
+ clock.advance(60 * 60 * 1000);
+ expect(d.checkStall().stalled).toBe(false); // cooldown is not enforced
+ });
+
+ it('disables enforcement when training transitions to sampling, re-arms warmup on return', () => {
+ const clock = makeClock();
+ const d = makeStallDetector({ now: clock.now, minStepSamples: 3, minBudgetMs: 90_000 });
+ d.observe('STAGE:training', clock.now());
+ for (let i = 1; i <= 4; i += 1) {
+ d.observe(`STEP:${i}:600:0.4`, clock.now());
+ clock.advance(10_000);
+ }
+ expect(d.getStepSamples()).toBeGreaterThanOrEqual(3);
+ // Mid-training sampling phase — long, legitimately silent.
+ d.observe('STAGE:sampling', clock.now());
+ clock.advance(10 * 60 * 1000);
+ expect(d.checkStall().stalled).toBe(false);
+ // Returning to training resets timing → warmup budget, samples cleared.
+ d.observe('STAGE:training', clock.now());
+ expect(d.getStepSamples()).toBe(0);
+ });
+
+ it('treats a STEP line as entering training even without a STAGE:training first', () => {
+ const clock = makeClock();
+ const d = makeStallDetector({ now: clock.now });
+ d.observe('STEP:1:600:0.4', clock.now());
+ expect(d.getPhase()).toBe('training');
+ });
+
+ it('does not trip during the gap between entering training and the first step (warmup)', () => {
+ const clock = makeClock();
+ const d = makeStallDetector({ now: clock.now, warmupBudgetMs: 20 * 60 * 1000 });
+ d.observe('STAGE:training', clock.now());
+ clock.advance(19 * 60 * 1000); // graph compile, no step yet — under warmup
+ expect(d.checkStall().stalled).toBe(false);
+ clock.advance(2 * 60 * 1000); // 21 min — past warmup, never stepped
+ expect(d.checkStall().stalled).toBe(true);
+ });
+
+ it('ignores blank lines', () => {
+ const clock = makeClock();
+ const d = makeStallDetector({ now: clock.now });
+ d.observe(' ', clock.now());
+ d.observe('', clock.now());
+ expect(d.getPhase()).toBe(null);
+ expect(d.checkStall().stalled).toBe(false);
+ });
+});