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
fix: reclaim killed test runs' temp roots as soon as their owner pid is gone (#9113)
[._.]/ Adam Eivy5280de06f56f
diff --git a/server/services/htmlComposition/index.test.js b/server/services/htmlComposition/index.test.jsindex 765d7c554f..329efe9123 100644--- a/server/services/htmlComposition/index.test.js+++ b/server/services/htmlComposition/index.test.js@@ -1,6 +1,6 @@-import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';import { existsSync } from 'node:fs';-import { mkdir, writeFile, readFile, readdir, symlink } from 'node:fs/promises';+import { mkdir, writeFile, readFile, readdir, rm, symlink } from 'node:fs/promises';import { join } from 'node:path';import { randomUUID } from 'node:crypto';import { execFileSync, spawn } from 'node:child_process';@@ -62,6 +62,17 @@ describe.skipIf(!chrome || !ffmpeg)('HTML composition with real Chrome and ffmpebrowserSession = await browser.newBrowserCDPSession();}, 30000);+ // Each render writes its composition dir, MP4 and thumbnail under the data+ // root; dropping them per test keeps the run root's peak size (and what a+ // killed run strands) small (#9113). The Chrome profile must survive.+ afterEach(async () => {+ await rm(join(PATHS.data, 'compositions'), { recursive: true, force: true });+ // Empty (not remove) the output dirs: later tests readdir them.+ for (const dir of [PATHS.videos, PATHS.videoThumbnails]) {+ for (const name of await readdir(dir).catch(() => [])) await rm(join(dir, name), { recursive: true, force: true });+ }+ });+afterAll(() => _cleanupTestBrowser({ browser, proc, cleanup: cleanupTempDataRoots }));it('awaits every seek, encodes exactly 12 frames, keeps the target hidden and registers a thumbnail', async () => {diff --git a/server/test/runTempRoot.js b/server/test/runTempRoot.jsindex 46fa816de9..4ae87f63a6 100644--- a/server/test/runTempRoot.js+++ b/server/test/runTempRoot.js@@ -21,6 +21,7 @@*/import { readdirSync, rmSync, statSync } from 'node:fs';import { join } from 'node:path';+import { OWNER_FILE } from './staleRunRoots.js';export function setup() {// No-op: server/vitest.config.js already created the root and pointed@@ -141,6 +142,7 @@ export function teardown() {}entries = entries+ .filter((name) => name !== OWNER_FILE) // the run's own owner stamp (#9113), not a leak.filter((name) => !VITEST_INTERNAL_SCRATCH_DIR.test(name)).filter((name) => !isEffectivelyEmpty(join(root, name)));diff --git a/server/test/staleRunRoots.js b/server/test/staleRunRoots.jsnew file mode 100644index 0000000000..8312812cef--- /dev/null+++ b/server/test/staleRunRoots.js@@ -0,0 +1,93 @@+/**+ * Owner-aware sweep of `pvt-*` run-scoped temp roots (#9113).+ *+ * `vitest.config.js` mints one root per run and stamps `.owner.pid` in it. A+ * killed run never reaches `teardown()` in `runTempRoot.js`, so its root is+ * left behind; the next config load calls `sweepStaleRunRoots()` to reclaim+ * it. A recorded owner that is provably gone frees the root immediately, an+ * owner that is alive keeps it however old it is (a >6h run must not be swept+ * from under itself), and a root whose owner cannot be determined falls back+ * to the conservative 6h age rule.+ */+import { execFileSync } from '../lib/childProcess.js';+import { readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';++export const OWNER_FILE = '.owner.pid';+export const STALE_ROOT_AGE_MS = 6 * 60 * 60 * 1000;+// `ps -o lstart=` has 1s resolution and the recorded start is derived from+// process.uptime(), so allow slack before calling a pid "reused".+const START_TOLERANCE_MS = 5000;++/** Record this process as the root's owner: `<pid> <start-ms>`. */+export function writeOwnerFile(root) {+ const startMs = Math.round(Date.now() - process.uptime() * 1000);+ writeFileSync(join(root, OWNER_FILE), `${process.pid} ${startMs}\n`);+}++/** Start time of a live pid in ms, or null when it cannot be read (always null on win32). */+function readProcessStartMs(pid) {+ if (process.platform === 'win32') return null;+ try {+ const out = execFileSync('ps', ['-o', 'lstart=', '-p', String(pid)], {+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'ignore'],+ env: { ...process.env, LC_ALL: 'C' },+ }).trim();+ const ms = Date.parse(out);+ return Number.isNaN(ms) ? null : ms;+ } catch {+ return null;+ }+}++/**+ * true = owner alive, false = owner gone (or pid reused), null = unknown.+ * `process.kill(pid, 0)` throws ESRCH for a missing pid and EPERM for a live+ * pid owned by someone else (alive).+ */+export function isOwnerAlive({ pid, startMs }) {+ try {+ process.kill(pid, 0);+ } catch (err) {+ if (err.code === 'ESRCH') return false;+ if (err.code !== 'EPERM') return null;+ }+ const liveStart = readProcessStartMs(pid);+ if (liveStart === null || !Number.isFinite(startMs)) return true;+ return Math.abs(liveStart - startMs) <= START_TOLERANCE_MS;+}++function readOwner(path) {+ try {+ const [pid, startMs] = readFileSync(join(path, OWNER_FILE), 'utf8').trim().split(/\s+/).map(Number);+ return Number.isInteger(pid) && pid > 0 ? { pid, startMs } : null;+ } catch {+ return null;+ }+}++export function sweepStaleRunRoots(tmpRoot, { now = Date.now(), probe = isOwnerAlive } = {}) {+ let names;+ try {+ names = readdirSync(tmpRoot);+ } catch {+ return; // unreadable tmp dir — skip rather than fail config load+ }+ for (const name of names) {+ if (!name.startsWith('pvt-')) continue;+ const path = join(tmpRoot, name);+ try {+ const stat = statSync(path);+ if (!stat.isDirectory()) continue;+ const owner = readOwner(path);+ const alive = owner ? probe(owner) : null;+ if (alive === true) continue;+ if (alive === false || now - stat.mtimeMs > STALE_ROOT_AGE_MS) {+ rmSync(path, { recursive: true, force: true });+ }+ } catch {+ // Already gone, or a permissions/race hiccup — best-effort sweep only.+ }+ }+}diff --git a/server/test/staleRunRoots.test.js b/server/test/staleRunRoots.test.jsnew file mode 100644index 0000000000..976696e765--- /dev/null+++ b/server/test/staleRunRoots.test.js@@ -0,0 +1,76 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { existsSync, mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { OWNER_FILE, STALE_ROOT_AGE_MS, isOwnerAlive, sweepStaleRunRoots, writeOwnerFile } from './staleRunRoots.js';++let host;+beforeEach(() => { host = mkdtempSync(join(tmpdir(), 'srr-test-')); });+afterEach(() => { rmSync(host, { recursive: true, force: true }); vi.restoreAllMocks(); });++const makeRoot = (name, { owner, ageMs = 0 } = {}) => {+ const root = join(host, name);+ mkdirSync(root);+ if (owner) writeFileSync(join(root, OWNER_FILE), owner);+ const t = new Date(Date.now() - ageMs);+ utimesSync(root, t, t);+ return root;+};++describe('sweepStaleRunRoots (#9113)', () => {+ it('removes a fresh root immediately when its owner is dead, keeps a live owner however old, and ages out pid-less roots at 6h', () => {+ const dead = makeRoot('pvt-dead', { owner: '111 1000' });+ const live = makeRoot('pvt-live', { owner: '222 1000', ageMs: STALE_ROOT_AGE_MS * 2 });+ const noPidFresh = makeRoot('pvt-nopid-fresh');+ const noPidOld = makeRoot('pvt-nopid-old', { ageMs: STALE_ROOT_AGE_MS + 60_000 });+ const garbageOld = makeRoot('pvt-garbage', { owner: 'not a pid', ageMs: STALE_ROOT_AGE_MS + 60_000 });+ const other = makeRoot('unrelated-old', { ageMs: STALE_ROOT_AGE_MS * 2 });++ sweepStaleRunRoots(host, { probe: ({ pid }) => pid === 222 });++ expect(existsSync(dead)).toBe(false);+ expect(existsSync(live)).toBe(true);+ expect(existsSync(noPidFresh)).toBe(true);+ expect(existsSync(noPidOld)).toBe(false);+ expect(existsSync(garbageOld)).toBe(false);+ expect(existsSync(other)).toBe(true);+ });++ it('falls back to the age rule when liveness is undeterminable (probe returns null)', () => {+ const fresh = makeRoot('pvt-unknown-fresh', { owner: '5 1' });+ const old = makeRoot('pvt-unknown-old', { owner: '5 1', ageMs: STALE_ROOT_AGE_MS + 60_000 });+ sweepStaleRunRoots(host, { probe: () => null });+ expect(existsSync(fresh)).toBe(true);+ expect(existsSync(old)).toBe(false);+ });++ it('keeps a root owned by this very process (real probe, real owner file)', () => {+ const root = makeRoot('pvt-self');+ writeOwnerFile(root);+ sweepStaleRunRoots(host);+ expect(existsSync(root)).toBe(true);+ });+});++describe('isOwnerAlive', () => {+ it('reports this process alive and a reused pid (mismatched start) dead', () => {+ const startMs = Date.now() - process.uptime() * 1000;+ expect(isOwnerAlive({ pid: process.pid, startMs })).toBe(true);+ if (process.platform !== 'win32') {+ expect(isOwnerAlive({ pid: process.pid, startMs: startMs - 3_600_000 })).toBe(false);+ }+ });++ it('treats ESRCH as dead and EPERM as alive', () => {+ const kill = vi.spyOn(process, 'kill');+ kill.mockImplementationOnce(() => { throw Object.assign(new Error('x'), { code: 'ESRCH' }); });+ expect(isOwnerAlive({ pid: 999999, startMs: 1 })).toBe(false);+ kill.mockImplementationOnce(() => { throw Object.assign(new Error('x'), { code: 'EPERM' }); });+ expect(isOwnerAlive({ pid: 1, startMs: NaN })).toBe(true);+ });++ it('does not throw on win32 and treats a signalable pid as alive', () => {+ vi.spyOn(process, 'platform', 'get').mockReturnValue('win32');+ expect(isOwnerAlive({ pid: process.pid, startMs: 1 })).toBe(true);+ });+});diff --git a/server/vitest.config.js b/server/vitest.config.jsindex 9cb72b0c86..f51202f445 100644--- a/server/vitest.config.js+++ b/server/vitest.config.js@@ -1,9 +1,10 @@import { defineConfig } from 'vitest/config';-import { mkdtempSync, readdirSync, rmSync, statSync } from 'node:fs';+import { mkdtempSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { vitestCiPool } from '../scripts/vitestCiPool.js';import { DB_TEST_INCLUDE } from './vitest.config.db.js';+import { sweepStaleRunRoots, writeOwnerFile } from './test/staleRunRoots.js';// `npm run test:fast` is the Windows-safe way to set the flag (a// `VITEST_FAST=1 vitest` script is parsed as an executable name on cmd.exe).@@ -26,12 +27,7 @@ if (process.env.npm_lifecycle_event === 'test:fast') {// below as globalSetup) is the other half: it reports and removes whatever is// left in the root after the run.//-// Stale-root sweep: remove `pvt-*` roots older than 6 hours from a PAST run-// that was killed before its teardown ran (a killed CoS agent, a crashed-// worker) — using the REAL tmpdir, before this run's own TMPDIR override-// below. A root from a run that is still in flight (started recently, by-// definition) survives; only the age check matters, not which process it-// belongs to, since two runs never share a root path.+// Stale-root sweep: see `test/staleRunRoots.js` (owner pid, 6h fallback).// Idempotency guard: `server/vitest.config.test.js` (and any other suite// that asserts on this file's own NODE_ENV-forcing behavior) dynamically// re-imports this module after `vi.resetModules()`, re-running every@@ -45,37 +41,17 @@ const REAL_TMPDIR = tmpdir();let RUN_TEMP_ROOT = process.env.PORTOS_TEST_TEMP_ROOT;if (!RUN_TEMP_ROOT) {- // Stale-root sweep: remove `pvt-*` roots older than 6 hours from a PAST run- // that was killed before its teardown ran (a killed CoS agent, a crashed- // worker) — using the REAL tmpdir, before this run's own TMPDIR override- // below. A root from a run that is still in flight (started recently, by- // definition) survives; only the age check matters, not which process it- // belongs to, since two runs never share a root path.- const STALE_ROOT_AGE_MS = 6 * 60 * 60 * 1000;- try {- const now = Date.now();- for (const name of readdirSync(REAL_TMPDIR)) {- if (!name.startsWith('pvt-')) continue;- const path = join(REAL_TMPDIR, name);- try {- const stat = statSync(path);- if (stat.isDirectory() && now - stat.mtimeMs > STALE_ROOT_AGE_MS) {- rmSync(path, { recursive: true, force: true });- }- } catch {- // Already gone, or a permissions/race hiccup — never fail config load- // over a best-effort sweep of someone else's stale root.- }- }- } catch {- // REAL_TMPDIR unreadable — skip the sweep rather than fail config load.- }+ // Stale-root sweep (#9113): reclaim `pvt-*` roots of killed runs — at once+ // when the recorded owner pid is gone, after 6h when no owner is recorded,+ // never while the owner lives. Uses the REAL tmpdir, before the override below.+ sweepStaleRunRoots(REAL_TMPDIR);// Short prefix: Unix-socket tests (e.g. services/itermBridge.test.js) build// a `join(tmpdir(), 'prefix-XXXXXX', 'name.sock')` path, and macOS caps// `sockaddr_un.sun_path` at 104 bytes — a long run-root prefix nested under// another temp dir could push a legitimate socket path over that limit.RUN_TEMP_ROOT = mkdtempSync(join(REAL_TMPDIR, 'pvt-'));+ writeOwnerFile(RUN_TEMP_ROOT);process.env.PORTOS_TEST_TEMP_ROOT = RUN_TEMP_ROOT;}process.env.TMPDIR = RUN_TEMP_ROOT;