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

fix(db): treat zombie writers as dead under non-reaping PID 1 (#10360)

Adam Eivy121fdda9bb64
diff --git a/server/lib/databaseMaintenanceWorker.test.js b/server/lib/databaseMaintenanceWorker.test.js
index f87a26e82c..8c0afa0f53 100644
--- a/server/lib/databaseMaintenanceWorker.test.js
+++ b/server/lib/databaseMaintenanceWorker.test.js
@@ -38,10 +38,12 @@ function installPm2Stub() {
{ name: 'portos-server', pmId: 13, pid: 1013, status: 'online', cwd: root, script: 'server/start.js' },
]));
const stubModule = join(stubs.dir, 'pm2.mjs');
+ const processAliveUrl = new URL('../test/processAlive.js', import.meta.url).href;
writeFileSync(stubModule, `import { appendFileSync, readFileSync, writeFileSync } from 'node:fs';
import { launchSurrogateServer, restartedServerEndpoint } from ${JSON.stringify(cutoverFixtureUrl)};
+import { isProcessAlive } from ${JSON.stringify(processAliveUrl)};
const state = ${JSON.stringify(state)};
-const alive = pid => { try { process.kill(pid, 0); return true; } catch { return false; } };
+const alive = isProcessAlive;
export async function listMaintenanceProcesses() {
return JSON.parse(readFileSync(state, 'utf8')).map(row => row.surrogate && !alive(row.pid) ? { ...row, status: 'errored', pid: 0 } : row);
}
diff --git a/server/lib/detachedSpawn.js b/server/lib/detachedSpawn.js
index 68833f8513..45d486546d 100644
--- a/server/lib/detachedSpawn.js
+++ b/server/lib/detachedSpawn.js
@@ -54,6 +54,7 @@
import { execFile, spawn } from './childProcess.js';
import { EventEmitter } from 'events';
import { constants as osConstants } from 'os';
+import { readFileSync } from 'node:fs';
import { basename, join } from 'path';
import { open, readFile, writeFile, rm, stat, readdir } from 'fs/promises';
import { promisify } from 'util';
@@ -81,7 +82,17 @@ const REAP_GRACE_MS = 12000;
const GROUP_KILL_MARKER = 'kill-process-group';
const isAlive = (pid) => {
- try { process.kill(pid, 0); return true; } catch { return false; }
+ try {
+ process.kill(pid, 0);
+ } catch {
+ return false;
+ }
+ try {
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
+ return stat.slice(stat.lastIndexOf(')') + 2, stat.lastIndexOf(')') + 3) !== 'Z';
+ } catch {
+ return true;
+ }
};
// Signal a detached job we hold no child handle for — the reparented POSIX
diff --git a/server/services/databaseMaintenanceCutover.test.js b/server/services/databaseMaintenanceCutover.test.js
index 272d96c61a..4f23ceca0c 100644
--- a/server/services/databaseMaintenanceCutover.test.js
+++ b/server/services/databaseMaintenanceCutover.test.js
@@ -43,9 +43,11 @@ const docker = { mode: 'docker', host: 'db.example.invalid', port: 5561, databas
// (#9368). Racing a clock against that startup made recovery flaky without
// exercising the cutover; `patient` returns the moment the proof lands, so it
// costs nothing when the host is healthy.
+import { isProcessAlive } from '../test/processAlive.js';
+
const fast = { graceMs: 1500, pollMs: 20, proofTimeoutMs: 4000 };
const patient = { ...fast, proofTimeoutMs: 30_000 };
-const alive = pid => { try { process.kill(pid, 0); return true; } catch { return false; } };
+const alive = isProcessAlive;
const processStart = async pid => process.platform === 'win32' ? null
: (await snapshotProcesses()).find(row => row.pid === pid)?.startedAt;
const savedEnv = { ...process.env };
diff --git a/server/services/databaseMaintenanceQuiescence.test.js b/server/services/databaseMaintenanceQuiescence.test.js
index 934857ef5e..485f4d74bc 100644
--- a/server/services/databaseMaintenanceQuiescence.test.js
+++ b/server/services/databaseMaintenanceQuiescence.test.js
@@ -28,8 +28,10 @@ const target = { ...source, mode: 'docker', port: 5561 };
const producers = ['portos-cos', 'portos-server'].map((name, pmId) => ({
name, pmId, pid: 100 + pmId, cwd: '/example/portos', script: `${name}.js`, status: 'online',
}));
+import { isProcessAlive } from '../test/processAlive.js';
+
const fast = { graceMs: 1500, pollMs: 20 };
-const alive = pid => { try { process.kill(pid, 0); return true; } catch { return false; } };
+const alive = isProcessAlive;
let root;
let journal;
let registry;
diff --git a/server/services/databaseMaintenanceTransfer.test.js b/server/services/databaseMaintenanceTransfer.test.js
index 7299ac78ce..7e69d3009d 100644
--- a/server/services/databaseMaintenanceTransfer.test.js
+++ b/server/services/databaseMaintenanceTransfer.test.js
@@ -36,12 +36,14 @@ const { createDatabaseMaintenanceJournal } = await import('../lib/databaseMainte
const { spawnDetached } = await import('../lib/detachedSpawn.js');
const { runDatabaseTransfer } = await import('./databaseMaintenanceTransfer.js');
+import { isProcessAlive } from '../test/processAlive.js';
+
const native = { mode: 'native', host: 'native.example.invalid', port: 5432, database: 'example_test', user: 'example' };
const docker = { mode: 'docker', host: 'docker.example.invalid', port: 5561, database: 'example_test', user: 'example' };
const fast = { graceMs: 1500, pollMs: 20 };
const endpointArgs = endpoint => `-h ${endpoint.host} -p ${endpoint.port} -U ${endpoint.user} -d ${endpoint.database}`;
const sha256 = text => createHash('sha256').update(text).digest('hex');
-const alive = pid => { try { process.kill(pid, 0); return true; } catch { return false; } };
+const alive = isProcessAlive;
const savedEnv = { ...process.env };
let root;
diff --git a/server/test/fixtures/databaseTransferStubs.js b/server/test/fixtures/databaseTransferStubs.js
index 7641533852..eb512d651a 100644
--- a/server/test/fixtures/databaseTransferStubs.js
+++ b/server/test/fixtures/databaseTransferStubs.js
@@ -51,7 +51,18 @@ ${phase('dump', 'start')}
trap '${phase('dump', 'exit')}' EXIT
writer=none
if [ -s "$R/writer.pid" ]; then
- if kill -0 "$(cat "$R/writer.pid")" 2>/dev/null; then writer=alive; else writer=dead; fi
+ wpid=$(cat "$R/writer.pid")
+ if kill -0 "$wpid" 2>/dev/null; then
+ if [ -f "/proc/$wpid/stat" ] && awk '{if ($NF=="") exit; sub(/^.*\)/, ""); if ($1=="Z") exit 1}' "/proc/$wpid/stat" 2>/dev/null; then
+ writer=alive
+ elif [ ! -f "/proc/$wpid/stat" ]; then
+ writer=alive
+ else
+ writer=dead
+ fi
+ else
+ writer=dead
+ fi
fi
echo "dump writer=$writer" >> "$R/events.log"
if [ "$mode" = pause ]; then ${pause('dump')}; fi
diff --git a/server/test/processAlive.test.js b/server/test/processAlive.test.js
new file mode 100644
index 0000000000..2a5fcc5d83
--- /dev/null
+++ b/server/test/processAlive.test.js
@@ -0,0 +1,97 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ readFileSync: vi.fn(),
+}));
+
+vi.mock('node:fs', () => ({
+ readFileSync: mocks.readFileSync,
+}));
+
+const { isProcessAlive } = await import('./processAlive.js');
+
+describe('isProcessAlive', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ mocks.readFileSync.mockReset();
+ });
+
+ it('reports this running process as alive', () => {
+ mocks.readFileSync.mockImplementation((path) => {
+ if (path === `/proc/${process.pid}/stat`) {
+ return `${process.pid} (node) R 1 2 3`;
+ }
+ const err = new Error('ENOENT');
+ err.code = 'ENOENT';
+ throw err;
+ });
+ expect(isProcessAlive(process.pid)).toBe(true);
+ });
+
+ it('reports a non-existent pid as dead', () => {
+ expect(isProcessAlive(1073741823)).toBe(false);
+ });
+
+ it('treats a zombie process (state Z in /proc/<pid>/stat) as dead on Linux', () => {
+ vi.spyOn(process, 'kill').mockImplementation((pid, sig) => {
+ if (pid === 12345 && sig === 0) return true;
+ throw new Error('ESRCH');
+ });
+
+ mocks.readFileSync.mockImplementation((path) => {
+ if (path === '/proc/12345/stat') {
+ return '12345 (sh) Z 1 12345 12345 0 -1 4194304 100 0 0 0 0 0 0 0 20 0 1 0 1000 0 0';
+ }
+ throw new Error('ENOENT');
+ });
+
+ expect(isProcessAlive(12345)).toBe(false);
+ });
+
+ it('treats a process with parentheses in command name and state Z as dead', () => {
+ vi.spyOn(process, 'kill').mockImplementation((pid, sig) => {
+ if (pid === 12345 && sig === 0) return true;
+ throw new Error('ESRCH');
+ });
+
+ mocks.readFileSync.mockImplementation((path) => {
+ if (path === '/proc/12345/stat') {
+ return '12345 (cmd (with parens) and spaces) Z 1 12345 12345 0 -1 4194304 100';
+ }
+ throw new Error('ENOENT');
+ });
+
+ expect(isProcessAlive(12345)).toBe(false);
+ });
+
+ it('treats an active process (state S or R in /proc/<pid>/stat) as alive', () => {
+ vi.spyOn(process, 'kill').mockImplementation((pid, sig) => {
+ if (pid === 12345 && sig === 0) return true;
+ throw new Error('ESRCH');
+ });
+
+ mocks.readFileSync.mockImplementation((path) => {
+ if (path === '/proc/12345/stat') {
+ return '12345 (worker) S 1 12345 12345 0 -1 4194304 100';
+ }
+ throw new Error('ENOENT');
+ });
+
+ expect(isProcessAlive(12345)).toBe(true);
+ });
+
+ it('falls back to process.kill(pid, 0) when /proc/<pid>/stat is unavailable (e.g. macOS)', () => {
+ vi.spyOn(process, 'kill').mockImplementation((pid, sig) => {
+ if (pid === 12345 && sig === 0) return true;
+ throw new Error('ESRCH');
+ });
+
+ mocks.readFileSync.mockImplementation(() => {
+ const err = new Error('ENOENT');
+ err.code = 'ENOENT';
+ throw err;
+ });
+
+ expect(isProcessAlive(12345)).toBe(true);
+ });
+});