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

test: reap cutover fixture servers before root cleanup (#9368)

[._.]/ Adam Eivyfcd70900c20f
diff --git a/server/lib/databaseMaintenanceWorker.test.js b/server/lib/databaseMaintenanceWorker.test.js
index edc5329b8c..d53f63436e 100644
--- a/server/lib/databaseMaintenanceWorker.test.js
+++ b/server/lib/databaseMaintenanceWorker.test.js
@@ -15,6 +15,7 @@ import { createDatabaseMaintenanceJournal } from './databaseMaintenanceJournal.j
import { createDatabaseWriterRegistry } from './databaseWriterRegistry.js';
import { STUB_DUMP_COMPLETE, installDatabaseStubs } from '../test/fixtures/databaseTransferStubs.js';
import { installCutoverStubs } from '../test/fixtures/databaseCutoverStubs.js';
+import { isProcessAlive } from '../test/processAlive.js';
const cutoverFixtureUrl = new URL('../test/fixtures/databaseCutoverStubs.js', import.meta.url).href;
@@ -88,9 +89,14 @@ beforeEach(() => {
NODE_OPTIONS: `--import=${installPm2Stub()}` };
delete env.VITEST;
});
-afterEach(() => {
+afterEach(async () => {
for (const group of strays) { try { process.kill(-group, 'SIGKILL'); } catch { /* already gone */ } }
- for (const pid of cutover.surrogatePids()) { try { process.kill(pid, 'SIGKILL'); } catch { /* already gone */ } }
+ const surrogates = cutover.surrogatePids();
+ for (const pid of surrogates) { try { process.kill(pid, 'SIGKILL'); } catch { /* already gone */ } }
+ // These servers deliberately outlive the coordinator. Their parent handles
+ // are gone, so teardown proves exit via the zombie-aware test probe before
+ // removing any files they could still write.
+ await vi.waitFor(() => expect(surrogates.some(isProcessAlive)).toBe(false), { timeout: 15_000, interval: 20 });
rmSync(root, { recursive: true, force: true });
});
diff --git a/server/services/databaseMaintenanceCutover.test.js b/server/services/databaseMaintenanceCutover.test.js
index 975f209185..ff9fe31cf8 100644
--- a/server/services/databaseMaintenanceCutover.test.js
+++ b/server/services/databaseMaintenanceCutover.test.js
@@ -88,10 +88,10 @@ beforeEach(() => {
PGHOST: 'inherited.example.invalid', PGPORT: '1', PGUSER: 'inherited', PGDATABASE: 'inherited',
PORTOS_NATIVE_PGPORT: '2', PGPORT_DOCKER: '3' });
});
-afterEach(() => {
+afterEach(async () => {
for (const key of Object.keys(process.env)) if (!(key in savedEnv)) delete process.env[key];
Object.assign(process.env, savedEnv);
- for (const pid of cutover?.surrogatePids() ?? []) { try { process.kill(pid, 'SIGKILL'); } catch { /* already gone */ } }
+ await cutover?.stopSurrogates();
context.root = undefined;
rmSync(root, { recursive: true, force: true });
});
diff --git a/server/test/fixtures/databaseCutoverStubs.js b/server/test/fixtures/databaseCutoverStubs.js
index 5d1b91e291..7b7a23d6bf 100644
--- a/server/test/fixtures/databaseCutoverStubs.js
+++ b/server/test/fixtures/databaseCutoverStubs.js
@@ -63,6 +63,12 @@ const log = line => appendFileSync(${JSON.stringify(events)}, line + '\\n');
// boot that was still pending (or never started) when the test gave up.
const trace = step => console.error(new Date().toISOString() + ' surrogate ' + process.pid + ' port ' + process.env.PGPORT + ' ' + step);
trace('started');
+// A killed Vitest worker cannot run afterEach. Its pipe closes even on
+// SIGKILL, so the owned surrogate exits instead of writing into a swept root.
+if (process.argv.includes('--owner-bound')) {
+ process.stdin.on('end', () => process.exit(0));
+ process.stdin.resume();
+}
try {
const { awaitDatabaseCutoverRelease } = await import(${JSON.stringify(handshakeUrl)});
const released = await awaitDatabaseCutoverRelease({ pollMs: 20, releaseTimeoutMs: 20000 });
@@ -80,13 +86,23 @@ setInterval(() => {}, 1000);
chmodSync(surrogate, 0o644);
const pidsPath = join(dir, 'surrogates');
+ const ownedServers = [];
return {
setHealth: value => writeFileSync(join(dir, 'pg-health'), value),
// Make the next stubbed PM2 restart hand the server this endpoint instead
// of the one the saved configuration names (a stale cached environment).
overrideRestartPool: endpoint => writeFileSync(join(dir, 'restart-pool.json'), JSON.stringify(endpoint)),
clearRestartPool: () => writeFileSync(join(dir, 'restart-pool.json'), 'null'),
- launchServer: endpoint => launchSurrogateServer(root, dir, endpoint),
+ // Ordinary fixture servers belong to the test worker. Keep their handles
+ // so teardown waits for exit before removing files they may still write.
+ launchServer: endpoint => launchSurrogateServer(root, dir, endpoint, child => {
+ const closed = new Promise(resolve => child.once('close', resolve));
+ ownedServers.push({ child, closed });
+ }),
+ stopSurrogates: () => Promise.all(ownedServers.map(({ child, closed }) => {
+ child.kill('SIGKILL');
+ return closed;
+ })),
surrogatePids: () => (existsSync(pidsPath) ? readFileSync(pidsPath, 'utf8').split('\n').filter(Boolean).map(Number) : []),
};
}
@@ -102,16 +118,25 @@ export function restartedServerEndpoint(root, dir) {
return endpoints[mode] ?? Object.values(endpoints)[0];
}
-/** A surrogate ordinary server whose pool is `endpoint`. Returns its pid. */
-export function launchSurrogateServer(root, dir, endpoint) {
+/**
+ * A surrogate ordinary server whose pool is `endpoint`. Returns its pid.
+ * onOwnedChild binds direct test launches to their worker's lifetime. The
+ * detached maintenance-worker fixture omits it: its restarted server must
+ * survive that coordinator's successful exit, like a real PM2 restart.
+ */
+export function launchSurrogateServer(root, dir, endpoint, onOwnedChild) {
const env = { ...process.env, NODE_ENV: 'test', PORTOS_DATA_ROOT: root,
PGHOST: endpoint.host, PGPORT: String(endpoint.port), PGDATABASE: endpoint.database, PGUSER: endpoint.user,
PGPASSWORD: 'example-password', NODE_OPTIONS: `--import=${pathToFileURL(join(dir, 'pg-register.mjs')).href}` };
delete env.VITEST;
const stderr = openSync(join(dir, 'surrogate-stderr.log'), 'a');
- const child = spawn(process.execPath, [join(dir, 'server-surrogate.mjs')], { env, stdio: ['ignore', 'ignore', stderr], detached: true });
+ const args = [join(dir, 'server-surrogate.mjs'), ...(onOwnedChild ? ['--owner-bound'] : [])];
+ const child = spawn(process.execPath, args, { env, stdio: [onOwnedChild ? 'pipe' : 'ignore', 'ignore', stderr], detached: true });
closeSync(stderr);
+ child.once('error', err => console.error('Cutover surrogate launch failed: ' + (err.code ?? 'error')));
+ onOwnedChild?.(child);
+ child.stdin?.unref();
child.unref();
- appendFileSync(join(dir, 'surrogates'), `${child.pid}\n`);
+ if (Number.isSafeInteger(child.pid)) appendFileSync(join(dir, 'surrogates'), `${child.pid}\n`);
return child.pid;
}
diff --git a/server/test/fixtures/databaseCutoverStubs.test.js b/server/test/fixtures/databaseCutoverStubs.test.js
new file mode 100644
index 0000000000..3ceea70830
--- /dev/null
+++ b/server/test/fixtures/databaseCutoverStubs.test.js
@@ -0,0 +1,84 @@
+// Fixture ownership regressions: normal teardown must finish child exit before
+// removing its root; a worker abort must not leave an active surrogate behind.
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { spawn } from 'node:child_process';
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { once } from 'node:events';
+import { installDatabaseStubs } from './databaseTransferStubs.js';
+import { installCutoverStubs } from './databaseCutoverStubs.js';
+import { isProcessAlive } from '../processAlive.js';
+import { sweepStaleRunRoots } from '../staleRunRoots.js';
+
+const source = { mode: 'native', host: 'db.example.invalid', port: 5432, database: 'example_test', user: 'example' };
+const target = { ...source, mode: 'docker', port: 5561 };
+const fixtureUrl = new URL('./databaseCutoverStubs.js', import.meta.url).href;
+const transferUrl = new URL('./databaseTransferStubs.js', import.meta.url).href;
+const rootsUrl = new URL('../staleRunRoots.js', import.meta.url).href;
+let container;
+let root;
+let cutover;
+let owner;
+let surrogate;
+
+beforeEach(() => {
+ container = mkdtempSync(join(tmpdir(), 'cutover-lifecycle-'));
+ root = mkdtempSync(join(container, 'pvt-'));
+ writeFileSync(join(root, '.portos-disposable-root'), '');
+});
+afterEach(async () => {
+ await cutover?.stopSurrogates();
+ if (owner?.exitCode === null && owner?.signalCode === null) {
+ const closed = once(owner, 'close');
+ owner.kill('SIGKILL');
+ await closed;
+ }
+ if (surrogate && isProcessAlive(surrogate)) process.kill(surrogate, 'SIGKILL');
+ rmSync(container, { recursive: true, force: true });
+ cutover = owner = surrogate = undefined;
+});
+const booted = () => existsSync(join(root, 'stubs', 'events.log'))
+ && readFileSync(join(root, 'stubs', 'events.log'), 'utf8').includes('server booted');
+const wait = assertion => vi.waitFor(assertion, { timeout: 15_000, interval: 20 });
+
+describe.skipIf(process.platform === 'win32')('cutover fixture ownership', () => {
+ it('awaits surrogate exit before the disposable root is removed', async () => {
+ const stubs = installDatabaseStubs(root);
+ cutover = installCutoverStubs(root, stubs.dir, { source, target });
+ surrogate = cutover.launchServer(target);
+ await wait(() => expect(booted()).toBe(true));
+ expect(isProcessAlive(surrogate)).toBe(true);
+ await cutover.stopSurrogates();
+ expect(isProcessAlive(surrogate)).toBe(false);
+ rmSync(root, { recursive: true, force: true });
+ expect(existsSync(root)).toBe(false);
+ });
+
+ it('exits when its worker is aborted, then allows the dead-owner root to be swept', async () => {
+ // The real fixture API runs in a separate owner, reproducing a Vitest
+ // worker killed before afterEach. No process-liveness mocks or DB calls.
+ const code = `import { writeFileSync } from 'node:fs';
+import { installDatabaseStubs } from ${JSON.stringify(transferUrl)};
+import { installCutoverStubs } from ${JSON.stringify(fixtureUrl)};
+import { writeOwnerFile } from ${JSON.stringify(rootsUrl)};
+const root = ${JSON.stringify(root)};
+writeOwnerFile(root);
+const stubs = installDatabaseStubs(root);
+const cutover = installCutoverStubs(root, stubs.dir, { source: ${JSON.stringify(source)}, target: ${JSON.stringify(target)} });
+writeFileSync(${JSON.stringify(join(root, 'surrogate.pid'))}, String(cutover.launchServer(${JSON.stringify(target)})));
+setInterval(() => {}, 1000);`;
+ owner = spawn(process.execPath, ['--input-type=module', '-e', code], { stdio: 'ignore' });
+ await wait(() => expect(booted()).toBe(true));
+ surrogate = Number(readFileSync(join(root, 'surrogate.pid'), 'utf8'));
+ expect(isProcessAlive(surrogate)).toBe(true);
+ sweepStaleRunRoots(container);
+ expect(existsSync(root)).toBe(true);
+ const closed = once(owner, 'close');
+ owner.kill('SIGKILL');
+ await closed;
+ await wait(() => expect(isProcessAlive(surrogate)).toBe(false));
+ sweepStaleRunRoots(container);
+ expect(existsSync(root)).toBe(false);
+ });
+});