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
keep LoRA training inside the unified-memory pool to stop swap-thrash reboots
[._.]/ Adam Eivy2ba7b3f879d9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex f658558192..56e9993296 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -42,6 +42,8 @@## Fixed+- **LoRA training stops oversubscribing unified memory — frees resident models, spills the latent cache to disk, and refuses to start when memory is too tight** — On a 128 GB Apple-Silicon box a single mflux FLUX.2 run pushed the machine to ~122 GB used + ~21 GB swap, and that swap-thrash coincided with the GPU watchdog reboots above. Three changes keep a run inside the unified-memory pool. (1) **Pre-train reclaim** — before spawning the trainer, PortOS unloads every model resident in Ollama and LM Studio (best-effort; failures are ignored) so their memory returns to the pool instead of stacking under the run. (2) **Latent cache always spills to disk** — the mflux `low_ram` flag is now on at every memory tier; keeping the encoded dataset cache in RAM bought nothing but the swap pressure, and disk-backing it costs only I/O, no training quality. (3) **Headroom gate** — the quantize/`low_ram` tier is now derived from the *post-unload available* memory (measured via `vm_stat` on macOS, free + inactive + speculative + purgeable) rather than raw RAM, so a busy box auto-tightens to a smaller base; and a run refuses to start with a clear error when under ~24 GB is free, rather than crashing the box mid-run. (`server/services/loraTraining/memoryPrep.js`, `server/services/loraTraining/runtimes.js`, `server/services/loraTraining/index.js`)+- **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 cpu_power,gpu_power,thermal` 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`)diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.mdindex 5b6fc6f7c0..5fd447e7e3 100644--- a/docs/TROUBLESHOOTING.md+++ b/docs/TROUBLESHOOTING.md@@ -305,6 +305,13 @@ thrash are secondary possibilities. First observed 2026-06-13 (twice in one day)resume rolls to a timestamped `powermetrics.<ts>.log` so the pre-crash log ispreserved) when passwordless `powermetrics` is configured (see the incidentrecord for the sudoers rule).+- Memory pressure is bounded before each run (`memoryPrep.js`): resident Ollama /+ LM Studio models are unloaded to free unified memory, the encoded-dataset cache+ always spills to disk (`low_ram`), the quantize tier is sized to *available*+ memory rather than total RAM, and a run refuses to start when under ~24 GB is+ free — so an oversubscribed run can't swap-thrash the box into a reboot. If a+ run won't start with a "not enough free memory" error, stop other model servers+ or close apps and retry.**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).diff --git a/docs/research/2026-06-13-mflux-training-watchdog-panic.md b/docs/research/2026-06-13-mflux-training-watchdog-panic.mdindex c481d4d5c3..a98c36a246 100644--- a/docs/research/2026-06-13-mflux-training-watchdog-panic.md+++ b/docs/research/2026-06-13-mflux-training-watchdog-panic.md@@ -68,6 +68,25 @@ swap thrash if a run oversubscribes unified memory.training proceeds. This gives the next crash a forensic record of GPU temp /power leading up to the hang.+3. **Unified-memory pressure mitigations** (`server/services/loraTraining/memoryPrep.js`)+ — directly attacks the swap-thrash secondary hypothesis. A 128 GB box was+ observed at ~122 GB used + ~21 GB swap during a single run, so before a run+ spawns PortOS now:+ - **Unloads resident models** — `prepareMemoryForTraining()` unloads every+ model resident in Ollama and LM Studio (best-effort) so their unified+ memory returns to the pool instead of stacking under the trainer. On a+ shared box this is the largest single reclaim.+ - **Spills the latent cache to disk at every tier** — `deriveMfluxMemoryConfig`+ now returns `low_ram: true` for all memory sizes (was `false` ≥64 GB). The+ in-RAM encoded-dataset cache bought nothing but swap pressure; disk-backing+ it costs only I/O, not training quality.+ - **Sizes the config to *available* memory + a hard floor** — the+ quantize/`low_ram` tier is derived from post-unload available memory+ (`vm_stat`: free + inactive + speculative + purgeable on macOS), not raw+ RAM, so a busy box auto-tightens to a smaller/quantized base. A run refuses+ to start (`failBeforeSpawn`) below `TRAINING_MIN_HEADROOM_GB` (24 GB)+ rather than swap-thrashing the machine into another reboot.+### Enabling the telemetry sidecar (passwordless powermetrics)`powermetrics` needs root. To let training capture telemetry without a prompt,diff --git a/server/services/loraTraining/index.js b/server/services/loraTraining/index.jsindex 5c6c260dab..aa8e8c6a48 100644--- a/server/services/loraTraining/index.js+++ b/server/services/loraTraining/index.js@@ -17,7 +17,7 @@ import { spawn } from 'child_process';import { existsSync } from 'fs';import { copyFile, mkdir, writeFile } from 'fs/promises';import { join, basename, dirname } from 'path';-import { platform, totalmem } from 'os';+import { platform } from 'os';import { PATHS, ensureDir, atomicWrite, shortId } from '../../lib/fileUtils.js';import { ServerError } from '../../lib/errorHandler.js';import { v4 as uuidv4 } from '../../lib/uuid.js';@@ -38,6 +38,7 @@ import {resolveTrainingRuntime,} from './runtimes.js';import { makeTrainingLineHandler } from './progress.js';+import { prepareMemoryForTraining, TRAINING_MIN_HEADROOM_GB } from './memoryPrep.js';import { classifyTrainingFailure } from './failure.js';import { buildTrainedSidecar, trainedLoraFilename } from './sidecar.js';import { validateDatasetReady } from './dataset.js';@@ -373,6 +374,22 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheckreturn failBeforeSpawn('Dataset was reassigned to a different character after this run was queued — cancel and retrain.');}+ // Reclaim unified memory before a GPU-heavy run, then gate on real headroom.+ // Training shares the unified-memory pool with resident LLMs and renders; an+ // oversubscribed run swap-thrashes and has coincided with GPU watchdog+ // reboots (docs/research/2026-06-13-mflux-training-watchdog-panic.md). We+ // unload resident models, measure what's actually free, and refuse to start+ // (rather than crash mid-run) when headroom is below the floor. The budget+ // also sizes the mflux quantize/low_ram tier below.+ const memReport = await prepareMemoryForTraining();+ if (memReport.unloaded.length) {+ console.log(`🧹 training [${shortId(jobId)}] freed ${memReport.unloaded.length} resident model(s): ${memReport.unloaded.join(', ')}`);+ }+ console.log(`🧮 training [${shortId(jobId)}] memory budget ${memReport.budgetGb.toFixed(0)} GB free of ${memReport.totalGb.toFixed(0)} GB total`);+ if (memReport.budgetGb < TRAINING_MIN_HEADROOM_GB) {+ return 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');@@ -438,9 +455,11 @@ export async function runTraining({ jobId, runId, pythonPath = null, resumeCheckdataDir,imageCount: manifest.images.length,outputDir: mfluxOutputDir,- // Memory-derived quantize/low_ram (see deriveMfluxMemoryConfig) —- // a bf16 base + in-RAM latent cache OOM-killed a 48 GB machine.- totalMemGb: totalmem() / 2 ** 30,+ // Memory-derived quantize/low_ram (see deriveMfluxMemoryConfig) keyed+ // on the post-unload AVAILABLE budget, not raw RAM — a bf16 base ++ // in-RAM latent cache OOM-killed a 48 GB machine, and on a shared box+ // resident models eat the same pool, so the tier must track headroom.+ totalMemGb: memReport.budgetGb,});const configPath = join(dir, 'mflux-train.json');await atomicWrite(configPath, config);diff --git a/server/services/loraTraining/memoryPrep.js b/server/services/loraTraining/memoryPrep.jsnew file mode 100644index 0000000000..b5152bad2b--- /dev/null+++ b/server/services/loraTraining/memoryPrep.js@@ -0,0 +1,113 @@+/**+ * Memory preparation for LoRA training runs.+ *+ * Training shares the Apple-Silicon unified-memory pool with every other+ * resident model server (ollama, LM Studio) and with PortOS itself. A run that+ * oversubscribes the pool swap-thrashes — ~21 GB of swap was live during the+ * GPU watchdog-timeout reboots documented in+ * docs/research/2026-06-13-mflux-training-watchdog-panic.md. Before spawning a+ * trainer we (1) unload resident LLMs to reclaim their memory and (2) measure+ * the real available headroom so the caller can size the run config to what's+ * actually free and refuse to start (rather than crash mid-run) when the pool+ * is too tight.+ *+ * Everything here is best-effort and never throws — a failed unload or an+ * unreadable vm_stat must not block training; it just yields a more+ * conservative (smaller) memory budget.+ */++import { execFile } from 'child_process';+import { promisify } from 'util';+import { platform, freemem, totalmem } from 'os';+import { getLoadedModels as ollamaLoadedModels, unloadModel as ollamaUnload } from '../ollamaManager.js';+import { getLoadedModels as lmStudioLoadedModels, unloadModel as lmStudioUnload } from '../lmStudioManager.js';++const execFileAsync = promisify(execFile);+const GB = 2 ** 30;++// Headroom floor: below this even a 4-bit 4B run risks swap-thrash, so refuse+// to start rather than reboot the box. Tuned for the smallest supported run;+// larger variants are protected by the budget-derived quantize/low_ram tiers.+export const TRAINING_MIN_HEADROOM_GB = 24;++/**+ * Best-effort: unload every model currently resident in ollama and LM Studio so+ * its unified memory returns to the pool before a training run. Each unload is+ * independent — failures (server down, model already expired) are swallowed.+ * Returns the list of freed model labels for logging. Never throws.+ */+export async function unloadResidentModels() {+ const unloaded = [];++ const ollamaLoaded = await ollamaLoadedModels().catch(() => []);+ for (const m of ollamaLoaded) {+ const name = m?.name || m?.id;+ if (!name) continue;+ const res = await ollamaUnload(name).catch(() => null);+ if (res?.unloaded) unloaded.push(`ollama:${name}`);+ }++ const lmLoaded = await lmStudioLoadedModels(true).catch(() => []);+ for (const m of lmLoaded) {+ if (!m?.id) continue;+ const res = await lmStudioUnload(m.id).catch(() => null);+ if (res?.success) unloaded.push(`lmstudio:${m.id}`);+ }++ return unloaded;+}++const parsePageSize = (out) => {+ const m = out.match(/page size of (\d+) bytes/);+ return m ? Number(m[1]) : 4096;+};++/**+ * Parse `vm_stat` for the memory macOS can actually hand to a new process —+ * free + inactive + speculative + purgeable pages (the same buckets Activity+ * Monitor reclaims under pressure). Node's freemem() counts only truly-free+ * pages and so wildly understates available unified memory on macOS, which+ * keeps most RAM as reclaimable cache. Returns GB, or null if unparseable.+ */+async function darwinAvailableGb() {+ const { stdout } = await execFileAsync('vm_stat');+ const pageSize = parsePageSize(stdout);+ const pages = (label) => {+ const m = stdout.match(new RegExp(`${label}:\\s+(\\d+)\\.`));+ return m ? Number(m[1]) : 0;+ };+ const available = pages('Pages free') + pages('Pages inactive')+ + pages('Pages speculative') + pages('Pages purgeable');+ if (!available) return null;+ return (available * pageSize) / GB;+}++/**+ * Memory the OS can realistically give a training run right now, in GB. Uses+ * vm_stat on darwin (unified-memory-aware), falling back to freemem() on other+ * platforms or any failure. Never throws.+ */+export async function getAvailableMemoryGb() {+ if (platform() === 'darwin') {+ const v = await darwinAvailableGb().catch(() => null);+ if (Number.isFinite(v) && v > 0) return v;+ }+ return freemem() / GB;+}++/**+ * Reclaim memory and report the budget for sizing/gating a training run:+ * - unloaded: labels of resident models freed+ * - availableGb: memory free after unloading+ * - totalGb: physical RAM+ * - budgetGb: what training may use (available, clamped to physical) — feed+ * this to deriveMfluxMemoryConfig so the quantize/low_ram tier reflects+ * real headroom, not raw RAM. Never throws.+ */+export async function prepareMemoryForTraining() {+ const unloaded = await unloadResidentModels().catch(() => []);+ const availableGb = await getAvailableMemoryGb().catch(() => 0);+ const totalGb = totalmem() / GB;+ const budgetGb = Math.min(totalGb, availableGb);+ return { unloaded, availableGb, totalGb, budgetGb };+}diff --git a/server/services/loraTraining/memoryPrep.test.js b/server/services/loraTraining/memoryPrep.test.jsnew file mode 100644index 0000000000..c43de89589--- /dev/null+++ b/server/services/loraTraining/memoryPrep.test.js@@ -0,0 +1,125 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Hoisted mock state so the factory closures below can reach it.+const h = vi.hoisted(() => ({+ ollamaLoaded: [],+ ollamaUnload: vi.fn(),+ lmLoaded: [],+ lmUnload: vi.fn(),+ platform: 'darwin',+ totalBytes: 128 * 2 ** 30,+ freeBytes: 8 * 2 ** 30,+ vmStat: { stdout: '' },+ vmStatThrows: false,+}));++vi.mock('../ollamaManager.js', () => ({+ getLoadedModels: vi.fn(async () => h.ollamaLoaded),+ unloadModel: (...a) => h.ollamaUnload(...a),+}));+vi.mock('../lmStudioManager.js', () => ({+ getLoadedModels: vi.fn(async () => h.lmLoaded),+ unloadModel: (...a) => h.lmUnload(...a),+}));+vi.mock('os', () => ({+ platform: () => h.platform,+ totalmem: () => h.totalBytes,+ freemem: () => h.freeBytes,+}));+vi.mock('child_process', () => ({+ execFile: (_cmd, cb) => {+ if (h.vmStatThrows) return cb(new Error('vm_stat missing'));+ return cb(null, h.vmStat);+ },+}));++const { unloadResidentModels, getAvailableMemoryGb, prepareMemoryForTraining, TRAINING_MIN_HEADROOM_GB } =+ await import('./memoryPrep.js');++// vm_stat with 16 KiB pages: free + inactive + speculative + purgeable pages+// sum to a known GB total so the parser assertion is exact.+const vmStatWith = (gb) => {+ const pages = (gb * 2 ** 30) / 16384;+ return `Mach Virtual Memory Statistics: (page size of 16384 bytes)+Pages free: ${Math.floor(pages / 4)}.+Pages active: 100000.+Pages inactive: ${Math.floor(pages / 4)}.+Pages speculative: ${Math.floor(pages / 4)}.+Pages wired down: 50000.+Pages purgeable: ${Math.ceil(pages / 4)}.+`;+};++beforeEach(() => {+ h.ollamaLoaded = [];+ h.lmLoaded = [];+ h.ollamaUnload = vi.fn(async () => ({ unloaded: true }));+ h.lmUnload = vi.fn(async () => ({ success: true }));+ h.platform = 'darwin';+ h.totalBytes = 128 * 2 ** 30;+ h.freeBytes = 8 * 2 ** 30;+ h.vmStat = { stdout: vmStatWith(100) };+ h.vmStatThrows = false;+});++describe('unloadResidentModels', () => {+ it('unloads every resident ollama + LM Studio model and labels them', async () => {+ h.ollamaLoaded = [{ name: 'llama3:70b' }, { id: 'qwen2.5' }];+ h.lmLoaded = [{ id: 'mlx-community/big' }];+ const freed = await unloadResidentModels();+ expect(freed).toEqual(['ollama:llama3:70b', 'ollama:qwen2.5', 'lmstudio:mlx-community/big']);+ expect(h.ollamaUnload).toHaveBeenCalledTimes(2);+ expect(h.lmUnload).toHaveBeenCalledWith('mlx-community/big');+ });++ it('swallows unload failures and omits the model from the freed list', async () => {+ h.ollamaLoaded = [{ name: 'a' }, { name: 'b' }];+ h.ollamaUnload = vi.fn()+ .mockResolvedValueOnce({ unloaded: false, reason: 'not loaded' })+ .mockRejectedValueOnce(new Error('server down'));+ const freed = await unloadResidentModels();+ expect(freed).toEqual([]);+ });++ it('returns empty when nothing is resident', async () => {+ expect(await unloadResidentModels()).toEqual([]);+ });+});++describe('getAvailableMemoryGb', () => {+ it('parses vm_stat (free+inactive+speculative+purgeable) on darwin', async () => {+ h.vmStat = { stdout: vmStatWith(64) };+ expect(await getAvailableMemoryGb()).toBeCloseTo(64, 0);+ });++ it('falls back to freemem() when vm_stat fails', async () => {+ h.vmStatThrows = true;+ h.freeBytes = 12 * 2 ** 30;+ expect(await getAvailableMemoryGb()).toBeCloseTo(12, 5);+ });++ it('uses freemem() off darwin', async () => {+ h.platform = 'linux';+ h.freeBytes = 7 * 2 ** 30;+ expect(await getAvailableMemoryGb()).toBeCloseTo(7, 5);+ });+});++describe('prepareMemoryForTraining', () => {+ it('clamps the budget to physical RAM and reports freed models', async () => {+ h.ollamaLoaded = [{ name: 'm' }];+ h.totalBytes = 96 * 2 ** 30;+ h.vmStat = { stdout: vmStatWith(200) }; // bogus over-report → clamp to total+ const r = await prepareMemoryForTraining();+ expect(r.unloaded).toEqual(['ollama:m']);+ expect(r.budgetGb).toBe(96);+ expect(r.totalGb).toBe(96);+ });++ it('budget tracks the post-unload available pool when below total', async () => {+ h.vmStat = { stdout: vmStatWith(40) };+ const r = await prepareMemoryForTraining();+ expect(r.budgetGb).toBeCloseTo(40, 0);+ expect(r.budgetGb).toBeLessThan(TRAINING_MIN_HEADROOM_GB + 100);+ });+});diff --git a/server/services/loraTraining/runtimes.js b/server/services/loraTraining/runtimes.jsindex 6a0105d2b2..9bf3d66bbe 100644--- a/server/services/loraTraining/runtimes.js+++ b/server/services/loraTraining/runtimes.js@@ -77,14 +77,20 @@ const MFLUX_SCHED = Object.freeze({ steps: 40, guidance: 1.0, timestepLow: 25, t* (videoGen/local.js): pure, with total RAM injected by the caller.* Training a bf16 base + in-RAM latent cache OOM-killed a 48 GB machine* during verification, so anything under 96 GB trains QLoRA-style against- * an on-the-fly-quantized base, and under 64 GB also spills the encoded- * dataset cache to disk (`low_ram`). Quantizing the FROZEN base is the- * standard QLoRA recipe — the LoRA weights themselves stay full precision.+ * an on-the-fly-quantized base. The encoded dataset cache ALWAYS spills to+ * disk (`low_ram`): keeping it in RAM bought nothing but pushed a 128 GB box+ * to 122 GB used + 21 GB swap (the swap-thrash that coincided with GPU+ * watchdog reboots — see docs/research/2026-06-13-mflux-training-watchdog-panic.md);+ * disk-backing it costs only I/O, no training quality. Quantizing the FROZEN+ * base is the standard QLoRA recipe — the LoRA weights stay full precision.+ *+ * Callers feed the *available* memory budget (post-unload, see memoryPrep.js),+ * not raw RAM, so the tier reflects real headroom on a shared box.*/export function deriveMfluxMemoryConfig(totalMemGb) {const gb = Number.isFinite(totalMemGb) ? totalMemGb : 0; // unknown → most conservative- if (gb >= 96) return { quantize: null, low_ram: false };- if (gb >= 64) return { quantize: 8, low_ram: false };+ if (gb >= 96) return { quantize: null, low_ram: true };+ if (gb >= 64) return { quantize: 8, low_ram: true };return { quantize: 4, low_ram: true };}diff --git a/server/services/loraTraining/runtimes.test.js b/server/services/loraTraining/runtimes.test.jsindex 05255f5d95..619cb33502 100644--- a/server/services/loraTraining/runtimes.test.js+++ b/server/services/loraTraining/runtimes.test.js@@ -117,9 +117,12 @@ describe('buildMfluxTrainConfig', () => {expect(() => buildMfluxTrainConfig({ ...base, imageCount: 0 })).toThrow(/at least one/);});- it('derives quantize/low_ram from total RAM (unknown → most conservative)', () => {- expect(deriveMfluxMemoryConfig(128)).toEqual({ quantize: null, low_ram: false });- expect(deriveMfluxMemoryConfig(64)).toEqual({ quantize: 8, low_ram: false });+ it('derives quantize from the memory budget; latent cache always spills to disk', () => {+ // low_ram is true at every tier — an in-RAM latent cache bought nothing+ // but risked swap-thrash (the 128 GB / 21 GB-swap incident). quantize still+ // steps down as the available budget shrinks.+ expect(deriveMfluxMemoryConfig(128)).toEqual({ quantize: null, low_ram: true });+ expect(deriveMfluxMemoryConfig(64)).toEqual({ quantize: 8, low_ram: true });expect(deriveMfluxMemoryConfig(48)).toEqual({ quantize: 4, low_ram: true });expect(deriveMfluxMemoryConfig(null)).toEqual({ quantize: 4, low_ram: true });const config = buildMfluxTrainConfig({ ...base, totalMemGb: 48 });