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

harden mflux LoRA training against mid-run GPU watchdog crashes

[._.]/ Adam Eivy0a4df627a9e9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index e9cdd67148..daa255d4e7 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -42,6 +42,8 @@
## Fixed
+- **LoRA training now survives a mid-run machine crash and self-instruments for GPU forensics** — Two GPU watchdog-timeout kernel panics (`watchdog timeout: no checkins from watchdogd in 90 seconds`) hard-rebooted the machine during mflux FLUX.2 training in a single day on M5 silicon (`Mac17,7`/`T6050`, macOS 26.5) — a system-level Metal/GPU hang, not a PortOS bug. Two changes make training resilient to it: (1) a checkpoint crash-resilience floor — `save_frequency` is now capped at `ceil(totalSteps/4)` (`MFLUX_MIN_CHECKPOINTS`) even when the user picks "only final save" (`checkpointEvery: 0`) or a huge interval, so a hard reboot loses at most ~¼ of a run instead of everything; resume from the newest checkpoint as before. (2) Each run streams `powermetrics --samplers gpu_power,thermal,smc` into `<run>/powermetrics.log` so the next crash leaves a forensic record of GPU temp/power leading up to the hang — gated on a non-interactive `sudo -n` probe so it no-ops cleanly (training unaffected) when passwordless `powermetrics` isn't configured. The incident, analysis, and an investigation checklist are documented in `docs/TROUBLESHOOTING.md` ("GPU watchdog kernel panic during LoRA training") + `docs/research/2026-06-13-mflux-training-watchdog-panic.md`. (`server/services/loraTraining/runtimes.js`, `scripts/train_mflux_lora.py`, `docs/TROUBLESHOOTING.md`, `docs/research/`)
+
- **Postgres pool no longer throws spurious "timeout exceeded when trying to connect"** — On a single-user box that periodically runs heavy local workloads (Ollama model pulls, CoS agents), establishing a fresh loopback connection could briefly exceed the 2s `connectionTimeoutMillis`, surfacing pool connection errors against a perfectly healthy Postgres. The connect timeout is raised to 10s (absorbs busy moments while still failing fast on a real outage) and `max` connections bumped 10→20 so concurrent in-process work isn't starved while one connection is slow to establish. (`server/lib/db.js`)
- **DB-adapter test suites run again — against a throwaway `portos_test`, never your real data** — Blocking the test runner from the production `portos` database (previous fix) left the 12 DB-backed adapter suites *skipping everywhere*: CI has no Postgres, and locally they're now refused on the real DB — so the universe/series/issue/story/writers-room/catalog/media DB layer had effectively zero executed coverage. This restores it the safe way. `npm run setup:db:test` provisions a throwaway `portos_test` database (creates it + applies `init-db.sql`), and `npm run test:db` runs just the DB-backed suites against it via a dedicated `vitest.config.db.js` that runs them serially (`fileParallelism: false`) so suites truncating the same tables can't clobber each other. CI now spins up a `pgvector/pgvector:pg17` service and runs those suites against `portos_test` on every PR — the default `npm test` still skips them (no test DB in scope), so nobody needs Postgres to run the rest of the suite and nobody's real `portos` is ever touched. A drift guard in `db.guards.test.js` fails if a new `checkHealth()`-gated suite is left out of the DB config (silently losing coverage). (`server/scripts/setup-db-test.mjs`, `server/vitest.config.db.js`, `server/lib/db.guards.test.js`, `.github/workflows/ci.yml`, `server/package.json`, `package.json`)
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index 382610b669..5774cc1424 100644
--- a/docs/TROUBLESHOOTING.md
+++ b/docs/TROUBLESHOOTING.md
@@ -278,6 +278,39 @@ npm test -- taskParser.test.js
npm run test:watch
```
+## Known Issues
+
+### GPU watchdog kernel panic during LoRA training
+
+**Symptom**: The whole machine hard-reboots while an mflux LoRA training run is
+active. After reboot you may see downstream PortOS errors — training failed with
+`SIGINT`/`KeyboardInterrupt`, `Tombstone sweep failed: timeout … connect`, CoS
+`xhr poll error`. The crash report under `/Library/Logs/DiagnosticReports/` reads:
+
+```
+panic(cpu N caller 0x…): watchdog timeout: no checkins from watchdogd in 90 seconds
+```
+
+**Cause**: A system-level hang (not a PortOS or training-script bug) — the machine
+stopped making forward progress long enough that the hardware watchdog
+force-rebooted it. On new Apple Silicon (M5 / `Mac17,7`) under sustained Metal/GPU
+load this is most likely a GPU/Metal driver hang; thermal/power or severe swap
+thrash are secondary possibilities. First observed 2026-06-13 (twice in one day).
+
+**Mitigations already in place**:
+- Training checkpoints at least every `ceil(totalSteps/4)` steps
+ (`MFLUX_MIN_CHECKPOINTS`), so a crash loses at most ~¼ of a run. Resume from the
+ newest `checkpoints/*.zip` via the UI's resume action or `--resume-checkpoint`.
+- Each run captures GPU/thermal/power telemetry to `<run>/powermetrics.log` when
+ passwordless `powermetrics` is configured (see the incident record for the
+ sudoers rule).
+
+**What to do / how to investigate**: see the full incident record and checklist in
+[`docs/research/2026-06-13-mflux-training-watchdog-panic.md`](research/2026-06-13-mflux-training-watchdog-panic.md).
+Short version: read the run's `powermetrics.log` (climbing GPU temp → cooling/power;
+log just stops at normal temps → driver hang), reduce batch size/resolution/rank as
+a test, and update macOS + `mflux`/`mlx`.
+
## Getting Help
1. **Check logs**: `pm2 logs` shows all process output
diff --git a/docs/research/2026-06-13-mflux-training-watchdog-panic.md b/docs/research/2026-06-13-mflux-training-watchdog-panic.md
new file mode 100644
index 0000000000..3f8d281d5b
--- /dev/null
+++ b/docs/research/2026-06-13-mflux-training-watchdog-panic.md
@@ -0,0 +1,105 @@
+# Incident: GPU watchdog-timeout kernel panic during mflux LoRA training
+
+**Status:** Open — monitoring for recurrence
+**First observed:** 2026-06-13 (two panics same day)
+**Affected:** `Mac17,7` (Apple Silicon, `T6050` SoC), macOS 26.5 (`Darwin 25.5.0`, `xnu-12377.121.6~2`)
+**Trigger:** Sustained GPU compute during mflux FLUX.2 LoRA training (`scripts/train_mflux_lora.py` → `mflux-train`)
+
+## Summary
+
+The machine hard-rebooted twice in one day, both times while a LoRA training run
+was active. Both crashes are **kernel watchdog-timeout panics** — the entire
+system stopped making forward progress long enough (90s) that the watchdog
+daemon could not check in, so the hardware watchdog force-rebooted the box. This
+is a *system-level hang*, not a fault in PortOS or the training script. The
+PortOS server errors seen afterward (training `SIGINT`/`KeyboardInterrupt`,
+`Tombstone sweep failed: timeout … connect`, `CoS Runner … xhr poll error`) are
+all downstream effects of the abrupt reboot.
+
+## Evidence
+
+Two panic reports under `/Library/Logs/DiagnosticReports/`, identical signature:
+
+| Time (local) | panicString | product | caller |
+|---|---|---|---|
+| 06:28:45 | `watchdog timeout: no checkins from watchdogd in 90 seconds` | `Mac17,7` | `0x…40a65d8c` |
+| 20:49:36 | `watchdog timeout: no checkins from watchdogd in 90 seconds` | `Mac17,7` | `0x…477fdd8c` |
+
+The two caller addresses differ **only by the ASLR kernel slide** — i.e. it is
+the same code path firing both times.
+
+Key fields from the 20:49 paniclog:
+
+- Panic backtrace top frames are in `com.apple.driver.AppleARMWatchdogTimer` and
+ `com.apple.driver.AppleInterruptControllerV3` — i.e. the watchdog itself, not
+ the originating fault. CPU 0 is just the core that serviced the timer.
+- `CORE 6–11 [MACC1] is offline` in **both** logs. This is almost certainly
+ normal idle power-gating of one cluster at panic time, not a hardware fault —
+ noted here only so a future investigator doesn't misread it.
+- `Compressor Info: 13% of compressed pages limit (OK) … 21 swapfiles and OK
+ swap space` — memory pressure was elevated but not critical at panic time, so
+ an OOM/swap-thrash root cause is possible but not strongly indicated.
+- `last started kext … com.apple.driver.AppleUVDMDriver` — unremarkable.
+
+## Analysis
+
+A `watchdogd` timeout means *nothing* could be scheduled for 90s — the strongest
+signal is a low-level stall rather than an ordinary userspace bug. Given the tight
+correlation with sustained Metal/GPU compute on **brand-new M5-class silicon
+(`T6050` / `Mac17,7`) running a ~6-week-old kernel (built 2026-04-27)**, the
+leading hypothesis is a **GPU/Metal driver hang under heavy ML load** — new-silicon
+GPU driver bugs commonly present exactly this way (whole system wedges → watchdog
+reboot). Secondary hypotheses: thermal/power-delivery trip, or severe
+swap thrash if a run oversubscribes unified memory.
+
+## Mitigations shipped (2026-06-13)
+
+1. **Checkpoint crash-resilience floor** — `MFLUX_MIN_CHECKPOINTS = 4` in
+ `server/services/loraTraining/runtimes.js`. `save_frequency` is now capped at
+ `ceil(totalSteps / 4)` even when the user picks "only final save"
+ (`checkpointEvery: 0`) or a very large interval, so a mid-run hard reboot
+ loses at most ~¼ of the run. Resume via the existing
+ `--resume-checkpoint <newest .zip>` path picks up from the last checkpoint.
+2. **GPU/thermal telemetry sidecar** — `TelemetrySidecar` in
+ `scripts/train_mflux_lora.py` streams `powermetrics --samplers
+ gpu_power,thermal,smc` into `<run>/powermetrics.log` for the life of each
+ training run. Gated on a non-interactive `sudo -n` probe: if passwordless
+ sudo for `powermetrics` is not configured it no-ops with a STATUS note and
+ training proceeds. This gives the next crash a forensic record of GPU temp /
+ power leading up to the hang.
+
+### Enabling the telemetry sidecar (passwordless powermetrics)
+
+`powermetrics` needs root. To let training capture telemetry without a prompt,
+add a sudoers rule (use `sudo visudo -f /etc/sudoers.d/portos-powermetrics`):
+
+```
+<your-username> ALL=(root) NOPASSWD: /usr/bin/powermetrics
+```
+
+Without this the sidecar simply skips capture — training is unaffected.
+
+## If it recurs — investigation checklist
+
+1. **Read the telemetry.** Open `<run>/powermetrics.log` from the crashed run.
+ - GPU die temp climbing toward ~100°C / SMC throttle flags set right before
+ the gap → **thermal/power**. Improve cooling, ensure high-watt AC adapter,
+ reduce load.
+ - Temps/power normal, log just stops → **driver hang**. Pursue an OS/mflux
+ update and file upstream.
+2. **Diff the new paniclog** against this record (`/Library/Logs/DiagnosticReports/
+ panic-full-*.panic`): same `watchdogd` signature + same caller (mod slide)
+ confirms the same fault.
+3. **Reduce sustained GPU pressure** as a controlled test — lower batch
+ size/resolution/rank (`TRAINING_DEFAULTS`) and see if the crash stops. If a
+ lighter run survives, intensity is the trigger.
+4. **Update the stack** — macOS point release, `pip install -U mflux mlx`. Search
+ the mflux / MLX issue trackers for `M5` / `watchdog` / `hang`.
+5. **Rule out hardware** only if the above don't resolve it — Apple Diagnostics
+ (boot holding **D**).
+
+## References
+
+- `docs/TROUBLESHOOTING.md` → "GPU watchdog kernel panic during LoRA training"
+- `scripts/train_mflux_lora.py` (`TelemetrySidecar`)
+- `server/services/loraTraining/runtimes.js` (`MFLUX_MIN_CHECKPOINTS`)
diff --git a/scripts/train_mflux_lora.py b/scripts/train_mflux_lora.py
index 310f267b15..1c7920aaa5 100644
--- a/scripts/train_mflux_lora.py
+++ b/scripts/train_mflux_lora.py
@@ -182,6 +182,62 @@ class ArtifactWatcher(threading.Thread):
self.scan() # final sweep after the child exits
+class TelemetrySidecar:
+ """Optional GPU/thermal/power capture for crash forensics.
+
+ macOS GPU watchdog-timeout kernel panics during sustained mflux training
+ (see docs/TROUBLESHOOTING.md "GPU watchdog kernel panic" + the incident
+ record under docs/research) hard-reboot the machine mid-run and leave NO
+ application-level record of GPU temperature / power draw leading up to the
+ hang. This streams `powermetrics` into <output_dir>/powermetrics.log so a
+ post-crash investigation can tell a thermal/power fault from a driver hang.
+
+ powermetrics requires root. We gate on a *non-interactive* `sudo -n` probe:
+ if passwordless sudo isn't configured the sidecar no-ops with a single
+ STATUS note and training proceeds unaffected — it never prompts or blocks.
+ """
+
+ SAMPLE_INTERVAL_MS = 5000
+
+ def __init__(self, output_dir: Path):
+ self.log_path = output_dir / "powermetrics.log"
+ self.proc = None
+
+ def start(self):
+ if sys.platform != "darwin" or not shutil.which("powermetrics"):
+ return
+ # `sudo -n true` returns non-zero (and prints nothing usable) when a
+ # password would be required — cheaper than letting powermetrics fail.
+ probe = subprocess.run(["sudo", "-n", "true"], capture_output=True)
+ if probe.returncode != 0:
+ log("STATUS:GPU telemetry disabled — passwordless sudo for powermetrics not configured; "
+ "see docs/TROUBLESHOOTING.md to enable thermal/power capture. Continuing without it.")
+ return
+ cmd = [
+ "sudo", "-n", "powermetrics",
+ "--samplers", "gpu_power,thermal,smc",
+ "-i", str(self.SAMPLE_INTERVAL_MS),
+ "--output-file", str(self.log_path),
+ ]
+ try:
+ self.proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ except OSError as err:
+ log(f"STATUS:GPU telemetry unavailable ({err}); continuing without it")
+ self.proc = None
+ return
+ log(f"STATUS:GPU telemetry → {self.log_path} (powermetrics @ {self.SAMPLE_INTERVAL_MS}ms)")
+
+ def stop(self):
+ if not self.proc or self.proc.poll() is not None:
+ return
+ # sudo forwards SIGTERM to powermetrics; escalate if it lingers.
+ self.proc.terminate()
+ try:
+ self.proc.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ self.proc.kill()
+
+
def find_adapter(checkpoints_dir: Path, output_dir: Path) -> Path | None:
"""Extract the lora adapter (`*_adapter.safetensors`, NOT the optimizer
state) from the newest checkpoint zip."""
@@ -235,6 +291,10 @@ def main():
watcher.start()
cmd = build_command(args.config, args.resume_checkpoint)
+ # Start telemetry only once we know the trainer command resolved (build_command
+ # exits early on a missing mflux) so we never leave an orphaned root process.
+ telemetry = TelemetrySidecar(output_dir)
+ telemetry.start()
log("STAGE:load-model")
log(f"STATUS:launching {Path(cmd[0]).name}")
CHILD = subprocess.Popen(
@@ -294,6 +354,7 @@ def main():
code = CHILD.wait()
watcher.stop_event.set()
watcher.join(timeout=10)
+ telemetry.stop()
if STOP_REQUESTED:
log("STATUS:canceled — last saved checkpoint retained")
diff --git a/server/services/loraTraining/runtimes.js b/server/services/loraTraining/runtimes.js
index 74f3c95a0d..6a0105d2b2 100644
--- a/server/services/loraTraining/runtimes.js
+++ b/server/services/loraTraining/runtimes.js
@@ -57,6 +57,15 @@ export const MFLUX_TRAIN_MODELS = Object.freeze({
'9b': 'flux2-klein-base-9b',
});
+// Crash-resilience floor: guarantee at least this many checkpoints across a
+// run regardless of the user's checkpointEvery. macOS GPU watchdog-timeout
+// kernel panics during sustained mflux training (see docs/TROUBLESHOOTING.md
+// "GPU watchdog kernel panic") hard-reboot the machine mid-run; without a
+// floor, checkpointEvery=0 ("only final save") or a very large interval means
+// such a crash discards the entire run. Capping the interval at
+// totalSteps/MIN_CHECKPOINTS bounds the worst-case loss to ~1/N of the run.
+export const MFLUX_MIN_CHECKPOINTS = 4;
+
// Noise-schedule shape for mflux base-model training — mirrors the official
// flux2 README example (steps 40, guidance 1.0, train the high-noise window
// [25, 40)). These are INFERENCE-schedule steps, distinct from the training
@@ -169,8 +178,11 @@ export function buildMfluxTrainConfig({
const totalSteps = p.steps;
const epochs = Math.max(1, Math.round(totalSteps / imageCount));
// save_frequency must be > 0; 0/absent checkpointEvery → only the final
- // save (frequency = total).
- const saveFrequency = p.checkpointEvery > 0 ? p.checkpointEvery : totalSteps;
+ // save (frequency = total). The crash-resilience floor then caps the
+ // interval so a hard reboot mid-run loses at most ~1/MIN_CHECKPOINTS of it.
+ const requestedSaveFrequency = p.checkpointEvery > 0 ? p.checkpointEvery : totalSteps;
+ const maxSaveInterval = Math.max(1, Math.ceil(totalSteps / MFLUX_MIN_CHECKPOINTS));
+ const saveFrequency = Math.min(requestedSaveFrequency, maxSaveInterval);
const memory = deriveMfluxMemoryConfig(totalMemGb);
return {
model: mfluxModel,
diff --git a/server/services/loraTraining/runtimes.test.js b/server/services/loraTraining/runtimes.test.js
index 2b30dc1654..05255f5d95 100644
--- a/server/services/loraTraining/runtimes.test.js
+++ b/server/services/loraTraining/runtimes.test.js
@@ -87,11 +87,25 @@ describe('buildMfluxTrainConfig', () => {
});
expect(config.optimizer.learning_rate).toBe(0.0002);
expect(config.max_resolution).toBe(768);
- expect(config.checkpoint.save_frequency).toBe(200); // only the final save
+ // checkpointEvery:0 would mean "only the final save", but the crash-
+ // resilience floor caps the interval at totalSteps/MIN_CHECKPOINTS (200/4).
+ expect(config.checkpoint.save_frequency).toBe(50);
expect(config.monitoring).toBeUndefined();
expect(config.lora_layers.targets[0].rank).toBe(8);
});
+ it('caps save_frequency at totalSteps/MIN_CHECKPOINTS for crash resilience', () => {
+ // A huge checkpointEvery (or 0 → "only final save") must still checkpoint
+ // periodically so a mid-run hard reboot (GPU watchdog panic) keeps progress.
+ const onlyFinal = buildMfluxTrainConfig({ ...base, params: { steps: 600, checkpointEvery: 0 } });
+ expect(onlyFinal.checkpoint.save_frequency).toBe(150); // ceil(600/4)
+ const tooLarge = buildMfluxTrainConfig({ ...base, params: { steps: 600, checkpointEvery: 9999 } });
+ expect(tooLarge.checkpoint.save_frequency).toBe(150);
+ // A reasonable user interval below the cap is left untouched.
+ const reasonable = buildMfluxTrainConfig({ ...base, params: { steps: 600, checkpointEvery: 100 } });
+ expect(reasonable.checkpoint.save_frequency).toBe(100);
+ });
+
it('enables monitoring with sample dimensions when sampleEvery > 0', () => {
const config = buildMfluxTrainConfig({ ...base, params: { sampleEvery: 50, resolution: 512 } });
expect(config.monitoring).toEqual({