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
address review (codex): only evict loopback-local model backends before training
[._.]/ Adam Eivyd848cfdd3fa9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 56e9993296..f9f5695052 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -42,7 +42,7 @@## 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 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. Only **loopback-local** backends are touched — a remote `OLLAMA_URL`/`LM_STUDIO_URL` (a LAN peer in a federated setup) is left alone, since evicting it would free no local memory. (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/`)diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.mdindex 5fd447e7e3..65a93d774c 100644--- a/docs/TROUBLESHOOTING.md+++ b/docs/TROUBLESHOOTING.md@@ -306,7 +306,8 @@ thrash are secondary possibilities. First observed 2026-06-13 (twice in one day)preserved) 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+ LM Studio models on loopback-local backends are unloaded to free unified memory+ (a remote LAN backend is left untouched), the encoded-dataset cachealways 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 isfree — so an oversubscribed run can't swap-thrash the box into a reboot. If adiff --git a/docs/research/2026-06-13-mflux-training-watchdog-panic.md b/docs/research/2026-06-13-mflux-training-watchdog-panic.mdindex a98c36a246..bf52aab6b4 100644--- a/docs/research/2026-06-13-mflux-training-watchdog-panic.md+++ b/docs/research/2026-06-13-mflux-training-watchdog-panic.md@@ -75,7 +75,9 @@ swap thrash if a run oversubscribes unified memory.- **Unloads resident models** — `prepareMemoryForTraining()` unloads everymodel resident in Ollama and LM Studio (best-effort) so their unifiedmemory returns to the pool instead of stacking under the trainer. On a- shared box this is the largest single reclaim.+ shared box this is the largest single reclaim. Only **loopback-local**+ backends are evicted — a remote `OLLAMA_URL`/`LM_STUDIO_URL` (LAN peer)+ is skipped, since unloading it frees no memory on the training machine.- **Spills the latent cache to disk at every tier** — `deriveMfluxMemoryConfig`now returns `low_ram: true` for all memory sizes (was `false` ≥64 GB). Thein-RAM encoded-dataset cache bought nothing but swap pressure; disk-backingdiff --git a/server/services/loraTraining/memoryPrep.js b/server/services/loraTraining/memoryPrep.jsindex b5152bad2b..bdc86e2506 100644--- a/server/services/loraTraining/memoryPrep.js+++ b/server/services/loraTraining/memoryPrep.js@@ -19,8 +19,8 @@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';+import { getLoadedModels as ollamaLoadedModels, unloadModel as ollamaUnload, getBaseUrl as ollamaBaseUrl } from '../ollamaManager.js';+import { getLoadedModels as lmStudioLoadedModels, unloadModel as lmStudioUnload, getBaseUrl as lmStudioBaseUrl } from '../lmStudioManager.js';const execFileAsync = promisify(execFile);const GB = 2 ** 30;@@ -30,28 +30,55 @@ const GB = 2 ** 30;// larger variants are protected by the budget-derived quantize/low_ram tiers.export const TRAINING_MIN_HEADROOM_GB = 24;+const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '0.0.0.0', '::1']);++/**+ * True only when `url` points at this machine's loopback interface. Unloading a+ * model frees memory on the box the backend RUNS on, not the box that issued+ * the request — and PortOS supports pointing `OLLAMA_URL` / `LM_STUDIO_URL` at a+ * remote LAN peer (a common federated-machines setup). Evicting a *remote*+ * backend would free no local unified memory and would destroy another box's+ * loaded model for nothing, so we only unload when the backend is local.+ * Unparseable or non-loopback → treated as remote (skip the unload). All of+ * 127.0.0.0/8 is loopback, so any `127.*` host counts.+ */+export function isLocalBackendUrl(url) {+ if (!url || !URL.canParse(url)) return false;+ // URL.hostname keeps the [...] brackets on IPv6 literals; strip them so the+ // `::1` loopback compares against LOOPBACK_HOSTS.+ const host = new URL(url).hostname.replace(/^\[|\]$/g, '');+ return LOOPBACK_HOSTS.has(host) || host.startsWith('127.');+}+/*** 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.+ * Skips a backend whose configured URL is NOT loopback-local: a remote backend+ * doesn't share this machine's memory, so evicting it would free nothing here+ * and needlessly drop a peer's loaded model. Returns the 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}`);+ if (isLocalBackendUrl(ollamaBaseUrl())) {+ 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}`);+ if (isLocalBackendUrl(lmStudioBaseUrl())) {+ 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;diff --git a/server/services/loraTraining/memoryPrep.test.js b/server/services/loraTraining/memoryPrep.test.jsindex c43de89589..1767c1de24 100644--- a/server/services/loraTraining/memoryPrep.test.js+++ b/server/services/loraTraining/memoryPrep.test.js@@ -4,8 +4,10 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';const h = vi.hoisted(() => ({ollamaLoaded: [],ollamaUnload: vi.fn(),+ ollamaUrl: 'http://localhost:11434',lmLoaded: [],lmUnload: vi.fn(),+ lmUrl: 'http://localhost:1234',platform: 'darwin',totalBytes: 128 * 2 ** 30,freeBytes: 8 * 2 ** 30,@@ -16,10 +18,12 @@ const h = vi.hoisted(() => ({vi.mock('../ollamaManager.js', () => ({getLoadedModels: vi.fn(async () => h.ollamaLoaded),unloadModel: (...a) => h.ollamaUnload(...a),+ getBaseUrl: () => h.ollamaUrl,}));vi.mock('../lmStudioManager.js', () => ({getLoadedModels: vi.fn(async () => h.lmLoaded),unloadModel: (...a) => h.lmUnload(...a),+ getBaseUrl: () => h.lmUrl,}));vi.mock('os', () => ({platform: () => h.platform,@@ -33,7 +37,7 @@ vi.mock('child_process', () => ({},}));-const { unloadResidentModels, getAvailableMemoryGb, prepareMemoryForTraining, TRAINING_MIN_HEADROOM_GB } =+const { unloadResidentModels, getAvailableMemoryGb, prepareMemoryForTraining, isLocalBackendUrl, TRAINING_MIN_HEADROOM_GB } =await import('./memoryPrep.js');// vm_stat with 16 KiB pages: free + inactive + speculative + purgeable pages@@ -55,6 +59,8 @@ beforeEach(() => {h.lmLoaded = [];h.ollamaUnload = vi.fn(async () => ({ unloaded: true }));h.lmUnload = vi.fn(async () => ({ success: true }));+ h.ollamaUrl = 'http://localhost:11434';+ h.lmUrl = 'http://localhost:1234';h.platform = 'darwin';h.totalBytes = 128 * 2 ** 30;h.freeBytes = 8 * 2 ** 30;@@ -84,6 +90,33 @@ describe('unloadResidentModels', () => {it('returns empty when nothing is resident', async () => {expect(await unloadResidentModels()).toEqual([]);});++ it('skips a remote backend — never evicts a peer machine\'s models', async () => {+ h.ollamaLoaded = [{ name: 'remote-llm' }];+ h.lmLoaded = [{ id: 'local-lm' }];+ h.ollamaUrl = 'http://10.0.0.5:11434'; // LAN peer — unloading frees no local memory+ h.lmUrl = 'http://127.0.0.1:1234'; // loopback — still eligible+ const freed = await unloadResidentModels();+ expect(freed).toEqual(['lmstudio:local-lm']);+ expect(h.ollamaUnload).not.toHaveBeenCalled();+ expect(h.lmUnload).toHaveBeenCalledWith('local-lm');+ });+});++describe('isLocalBackendUrl', () => {+ it('accepts loopback hosts (incl. 127.0.0.0/8 and IPv6)', () => {+ for (const u of [+ 'http://localhost:11434', 'http://127.0.0.1:1234', 'http://127.0.0.53:1234',+ 'http://0.0.0.0:1234', 'http://[::1]:1234',+ ]) expect(isLocalBackendUrl(u)).toBe(true);+ });++ it('rejects LAN/remote hosts and unparseable input', () => {+ for (const u of [+ 'http://10.0.0.5:11434', 'http://192.168.1.20:1234', 'http://peer.local:11434',+ 'http://example.com', '', null, undefined, 'not a url',+ ]) expect(isLocalBackendUrl(u)).toBe(false);+ });});describe('getAvailableMemoryGb', () => {