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

stop pm2.savedProcesses.test.js forking a real PM2 daemon per run, and bound every pm2 app's memory

[._.]/ Adam Eivya439ff9f1ec6
diff --git a/.env.example b/.env.example
index 655033ded1..f0d3406af7 100644
--- a/.env.example
+++ b/.env.example
@@ -30,6 +30,11 @@ PGPASSWORD=portos
# session / heavy SSE load doesn't cause spurious restarts (e.g. 32G on 128 GB).
# PORTOS_SERVER_MAX_MEMORY=32G
+# Same ceiling for the Vite dev server (portos-ui). Default 1G — a dev server that
+# transforms modules on demand should sit well under that; raise it only if a huge
+# client tree makes Vite restart during normal editing.
+# PORTOS_UI_MAX_MEMORY=2G
+
# Override the base URLs advertised to clients (auto-derived from PORTOS_HOST/PORT if unset)
# PORTOS_API_URL=https://my-machine.ts.net:5555
# PORTOS_UI_URL=https://my-machine.ts.net:5555
diff --git a/ecosystem.config.cjs b/ecosystem.config.cjs
index be3c06d7cf..39cd28263d 100644
--- a/ecosystem.config.cjs
+++ b/ecosystem.config.cjs
@@ -12,19 +12,22 @@ const BASE_ENV = {
};
// Read a couple of machine-local settings from .env (pm2 doesn't auto-load it
-// here): PGMODE → PostgreSQL port; PORTOS_SERVER_MAX_MEMORY → the restart ceiling
-// below. An explicit process.env wins over the .env file so a one-off shell
-// override still works.
+// here): PGMODE → PostgreSQL port; PORTOS_SERVER_MAX_MEMORY / PORTOS_UI_MAX_MEMORY
+// → the restart ceilings below. An explicit process.env wins over the .env file
+// so a one-off shell override still works.
const fs = require('fs');
const envFile = path.join(__dirname, '.env');
let pgMode = 'docker';
-let envMaxMemory = null;
+let envServerMaxMemory = null;
+let envUiMaxMemory = null;
try {
const envContent = fs.readFileSync(envFile, 'utf8');
const modeMatch = envContent.match(/^PGMODE=(\w+)/m);
if (modeMatch) pgMode = modeMatch[1];
const memMatch = envContent.match(/^PORTOS_SERVER_MAX_MEMORY=(\S+)/m);
- if (memMatch) envMaxMemory = memMatch[1];
+ if (memMatch) envServerMaxMemory = memMatch[1];
+ const uiMemMatch = envContent.match(/^PORTOS_UI_MAX_MEMORY=(\S+)/m);
+ if (uiMemMatch) envUiMaxMemory = uiMemMatch[1];
} catch { /* no .env file — default to docker */ }
// pm2 restarts portos-server when its RSS crosses this — originally a memory-leak
@@ -35,7 +38,61 @@ try {
// streams and long jobs. (Training is no longer collateral damage from these
// restarts — it's spawned detached into its own process group — but fewer
// restarts is still better.)
-const SERVER_MAX_MEMORY = process.env.PORTOS_SERVER_MAX_MEMORY || envMaxMemory || '4G';
+const SERVER_MAX_MEMORY = process.env.PORTOS_SERVER_MAX_MEMORY || envServerMaxMemory || '4G';
+
+// Same idea for the Vite dev server. It had NO ceiling at all and was observed at
+// 2.7 GB after 18h of uptime — a dev server that only transforms modules on
+// demand has no business holding gigabytes.
+const UI_MAX_MEMORY = process.env.PORTOS_UI_MAX_MEMORY || envUiMaxMemory || '1G';
+
+// The support daemons (autofixer, its UI, the browser bridge) idle around 45 MB.
+// A ceiling an order of magnitude above that never fires in normal operation and
+// still catches a runaway.
+const HELPER_MAX_MEMORY = '512M';
+
+// The CoS runner supervises long-lived agent CLI children; the ceiling covers the
+// runner itself, not the agents (they are separate processes with their own RSS).
+const COS_MAX_MEMORY = '2G';
+
+const MEMORY_UNIT_MB = { K: 1 / 1024, M: 1, G: 1024 };
+
+/**
+ * Parse a pm2 memory spec ('512M', '4G', '1024') to megabytes.
+ * pm2 itself defaults a bare number to bytes, but every spec here carries a unit
+ * and an unrecognized one returns null so `heapCapArgs` degrades to "no cap"
+ * rather than silently inventing a wrong one.
+ */
+function memorySpecToMB(spec) {
+ const match = String(spec).trim().match(/^(\d+(?:\.\d+)?)\s*([KMG])B?$/i);
+ if (!match) return null;
+ return Math.round(Number(match[1]) * MEMORY_UNIT_MB[match[2].toUpperCase()]);
+}
+
+/**
+ * V8's old-space cap for a pm2 app, as `node_args`.
+ *
+ * WHY: without an explicit cap, V8 sizes the heap limit from physical memory and
+ * lands at ~4 GB on any workstation. That is at or above every ceiling below, so
+ * the process reaches `max_memory_restart` and gets KILLED before V8 ever feels
+ * enough pressure to run the full compacting GC that would have reclaimed the
+ * garbage. Capping the heap under the pm2 ceiling inverts that race: V8 collects,
+ * RSS settles, and the restart stays a genuine last resort instead of the normal
+ * way memory is reclaimed — which matters because a restart drops in-flight SSE
+ * streams and long jobs.
+ *
+ * 75% leaves room for the non-heap RSS (native buffers, sharp, the module code
+ * itself) under the same ceiling.
+ *
+ * `node_args` rather than `NODE_OPTIONS` on purpose: NODE_OPTIONS is inherited by
+ * every child process, so it would also shrink the heap of the agent CLIs, build
+ * steps, and media tooling portos-server spawns. `node_args` applies to the
+ * interpreter pm2 launches and stops there.
+ */
+function heapCapArgs(restartSpec) {
+ const ceilingMB = memorySpecToMB(restartSpec);
+ if (!ceilingMB) return [];
+ return [`--max-old-space-size=${Math.max(256, Math.floor(ceilingMB * 0.75))}`];
+}
const PORTS = {
API: 5555, // Express API server (HTTPS when Tailscale cert is active)
@@ -113,6 +170,7 @@ module.exports = {
// `'**/.cache/**'`, `'**/portos-stepwise-*/**'`) to `ignore_watch`.
watch: false,
max_memory_restart: SERVER_MAX_MEMORY,
+ node_args: heapCapArgs(SERVER_MAX_MEMORY),
// PM2's default kill_timeout (1600ms) is shorter than the server's own
// GRACEFUL_SHUTDOWN_TIMEOUT_MS (10s) force-exit in server/index.js, so if
// shutdown ever stalls, PM2 would SIGKILL the process before its graceful
@@ -152,7 +210,8 @@ module.exports = {
max_restarts: 5,
min_uptime: '30s',
restart_delay: 10000,
- max_memory_restart: '2G',
+ max_memory_restart: COS_MAX_MEMORY,
+ node_args: heapCapArgs(COS_MAX_MEMORY),
// Important: This process manages long-running agent processes
// Keep kill_timeout high to allow graceful shutdown of agents
kill_timeout: 30000
@@ -168,7 +227,15 @@ module.exports = {
...BASE_ENV,
VITE_PORT: PORTS.UI
},
- watch: false
+ watch: false,
+ // Vite's dev server keeps a module graph, a transform cache, and per-client
+ // HMR bookkeeping that all grow with session length, and it never releases
+ // them on its own. With the default (physical-memory-derived) heap limit it
+ // was measured at 2.7 GB after 18h. The heap cap makes V8 actually collect;
+ // the ceiling restarts a dev server that still runs away. A restart here is
+ // cheap — the browser reconnects and Vite re-warms its transform cache.
+ max_memory_restart: UI_MAX_MEMORY,
+ node_args: heapCapArgs(UI_MAX_MEMORY)
},
{
name: 'portos-autofixer',
@@ -186,7 +253,9 @@ module.exports = {
autorestart: true,
max_restarts: 10,
min_uptime: '10s',
- restart_delay: 5000
+ restart_delay: 5000,
+ max_memory_restart: HELPER_MAX_MEMORY,
+ node_args: heapCapArgs(HELPER_MAX_MEMORY)
},
{
name: 'portos-autofixer-ui',
@@ -203,7 +272,9 @@ module.exports = {
autorestart: true,
max_restarts: 10,
min_uptime: '10s',
- restart_delay: 5000
+ restart_delay: 5000,
+ max_memory_restart: HELPER_MAX_MEMORY,
+ node_args: heapCapArgs(HELPER_MAX_MEMORY)
},
{
name: 'portos-browser',
@@ -224,7 +295,9 @@ module.exports = {
autorestart: true,
max_restarts: 10,
min_uptime: '10s',
- restart_delay: 5000
+ restart_delay: 5000,
+ max_memory_restart: HELPER_MAX_MEMORY,
+ node_args: heapCapArgs(HELPER_MAX_MEMORY)
}
]
};
diff --git a/server/lib/ecosystemMemory.test.js b/server/lib/ecosystemMemory.test.js
new file mode 100644
index 0000000000..9c4b0927e7
--- /dev/null
+++ b/server/lib/ecosystemMemory.test.js
@@ -0,0 +1,51 @@
+import { describe, it, expect } from 'vitest';
+import { createRequire } from 'module';
+import { fileURLToPath } from 'url';
+import path from 'path';
+
+/**
+ * Every pm2 app needs BOTH memory bounds, and they have to be in the right order.
+ *
+ * `max_memory_restart` alone is not a memory policy — it is only the kill switch.
+ * Node sizes V8's heap limit from physical memory (~4 GB on any workstation), so
+ * without an explicit `--max-old-space-size` the process hits the pm2 ceiling
+ * before V8 ever runs the full compacting GC that would have reclaimed the
+ * garbage: the restart becomes the routine way memory is freed, and every restart
+ * drops in-flight SSE streams and long jobs.
+ *
+ * portos-ui shipped with neither bound and was measured at 2.7 GB after 18h of
+ * uptime — the regression these assertions exist to prevent.
+ */
+const require = createRequire(import.meta.url);
+const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
+const { apps } = require(path.join(repoRoot, 'ecosystem.config.cjs'));
+
+const UNIT_MB = { K: 1 / 1024, M: 1, G: 1024 };
+const toMB = (spec) => {
+ const match = String(spec).trim().match(/^(\d+(?:\.\d+)?)\s*([KMG])B?$/i);
+ return match ? Number(match[1]) * UNIT_MB[match[2].toUpperCase()] : null;
+};
+
+const heapCapMB = (app) => {
+ const flag = (app.node_args || []).find((a) => a.startsWith('--max-old-space-size='));
+ return flag ? Number(flag.split('=')[1]) : null;
+};
+
+describe('ecosystem.config.cjs memory bounds', () => {
+ it.each(apps.map((app) => [app.name, app]))('%s declares a restart ceiling', (_name, app) => {
+ expect(toMB(app.max_memory_restart)).toBeGreaterThan(0);
+ });
+
+ it.each(apps.map((app) => [app.name, app]))('%s caps V8 below that ceiling', (_name, app) => {
+ const cap = heapCapMB(app);
+ expect(cap).toBeGreaterThan(0);
+ // Strictly below, so V8 collects first and pm2 restarts only as a last resort.
+ expect(cap).toBeLessThan(toMB(app.max_memory_restart));
+ });
+
+ // A heap cap must never reach the child processes portos-server spawns (agent
+ // CLIs, builds, media tooling) — NODE_OPTIONS is inherited, `node_args` is not.
+ it.each(apps.map((app) => [app.name, app]))('%s sets the cap via node_args, not NODE_OPTIONS', (_name, app) => {
+ expect(app.env?.NODE_OPTIONS ?? '').not.toContain('max-old-space-size');
+ });
+});
diff --git a/server/services/pm2.savedProcesses.test.js b/server/services/pm2.savedProcesses.test.js
index 7242402943..930c443a02 100644
--- a/server/services/pm2.savedProcesses.test.js
+++ b/server/services/pm2.savedProcesses.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { EventEmitter } from 'events';
import { mkdtemp, rm, writeFile } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
@@ -7,8 +8,31 @@ import { join } from 'path';
// call is made). Mocked to keep the import side-effect-free in CI.
vi.mock('pm2', () => ({ default: { connect: vi.fn(), list: vi.fn(), disconnect: vi.fn() } }));
+// `saveProcessList` runs `pm2 save` through pm2.js's OWN `execPm2`, and an
+// intra-module call reads the local binding — a `vi.spyOn(pm2Module, 'execPm2')`
+// never intercepts it (that only works for the cross-module callers in
+// mtplxServerManager / llamaServerManager). This test used to rely on that spy,
+// so every run really launched `pm2 save` against the throwaway PM2_HOME below,
+// and PM2 answered by forking a God Daemon that outlived the suite. Those
+// daemons never exit: 641 of them (38 GB of RSS) had accumulated on the dev
+// machine that reported this. Mocking the spawn seam — the same one
+// pm2.launch.test.js uses — is what actually keeps the subprocess out.
+const mockSpawn = vi.hoisted(() => vi.fn());
+vi.mock('../lib/childProcess.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ spawn: mockSpawn,
+}));
+
import { getSavedProcessNames, saveProcessList } from './pm2.js';
-import * as pm2Module from './pm2.js';
+
+// Fake child_process.spawn result: closes with exit code 0 on the next tick.
+function fakeChild() {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ queueMicrotask(() => child.emit('close', 0));
+ return child;
+}
/**
* `getSavedProcessNames` reads `$PM2_HOME/dump.pm2` — the list a boot-time
@@ -68,19 +92,34 @@ describe('saveProcessList exclusions', () => {
beforeEach(async () => {
home = await mkdtemp(join(tmpdir(), 'portos-pm2-home-'));
- // `pm2 save` itself is the real subprocess; the dump it would have written
- // is seeded per test so the filtering is what's under assertion.
- vi.spyOn(pm2Module, 'execPm2').mockResolvedValue({ stdout: '', stderr: '' });
+ // `pm2 save` is stubbed out at the spawn seam; the dump it would have
+ // written is seeded per test so the filtering is what's under assertion.
+ mockSpawn.mockReset();
+ mockSpawn.mockImplementation(() => fakeChild());
});
afterEach(async () => {
- vi.restoreAllMocks();
await rm(home, { recursive: true, force: true });
});
const seedDump = (names) =>
writeFile(join(home, 'dump.pm2'), JSON.stringify(names.map((name) => ({ name, script: `/bin/${name}` }))));
+ // Regression guard for the daemon leak described at the top of this file. If a
+ // future refactor moves `pm2 save` off the mocked `spawn` seam, this assertion
+ // fails loudly here instead of quietly forking a real PM2 God Daemon per test
+ // that survives the run forever.
+ it('runs `pm2 save` through the stubbed spawn seam, never a real subprocess', async () => {
+ await seedDump(['portos-server']);
+
+ await saveProcessList(home);
+
+ expect(mockSpawn).toHaveBeenCalledTimes(1);
+ const [, args, opts] = mockSpawn.mock.calls[0];
+ expect(args.at(-1)).toBe('save');
+ expect(opts.env.PM2_HOME).toBe(home);
+ });
+
it('drops an excluded app from the dump and leaves the rest', async () => {
await seedDump(['portos-server', 'portos-llama-server', 'portos-mtplx']);