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
test: own and diagnose offline transfer fixture children (#10329)
[._.]/ Adam Eivy298c7cf4518a
diff --git a/server/services/databaseMaintenanceTransfer.test.js b/server/services/databaseMaintenanceTransfer.test.jsindex 8c180a442a..7299ac78ce 100644--- a/server/services/databaseMaintenanceTransfer.test.js+++ b/server/services/databaseMaintenanceTransfer.test.js@@ -10,7 +10,7 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { STUB_DUMP_COMPLETE, installDatabaseStubs } from '../test/fixtures/databaseTransferStubs.js';-const context = vi.hoisted(() => ({ root: undefined, list: null, stop: null }));+const context = vi.hoisted(() => ({ root: undefined, list: null, stop: null, timed: null }));vi.mock('../lib/paths.js', async original => {const actual = await original();return { ...actual, PATHS: new Proxy(actual.PATHS, {@@ -21,6 +21,13 @@ vi.mock('../lib/paths.js', async original => {},}) };});+// Only the process-table snapshot is wrapped (timed per call); every behavior+// is the real one. It is the harness's one real `ps -A` and the first suspect+// when a case is slow under load.+vi.mock('../lib/detachedSpawn.js', async original => {+ const actual = await original();+ return { ...actual, snapshotProcesses: (...args) => context.timed('snapshotProcesses', () => actual.snapshotProcesses(...args)) };+});vi.mock('./pm2.js', () => ({listMaintenanceProcesses: (...args) => context.list(...args),stopApp: (...args) => context.stop(...args),@@ -44,28 +51,32 @@ let rows;let operation;let token;let strays;+let ordinary;-beforeEach(() => {+beforeEach(({ onTestFailed }) => {root = mkdtempSync(join(tmpdir(), 'database-transfer-'));writeFileSync(join(root, '.portos-disposable-root'), '');mkdirSync(join(root, 'server', 'cos-runner'), { recursive: true });writeFileSync(join(root, 'server', 'start.js'), '');writeFileSync(join(root, 'server', 'cos-runner', 'index.js'), '');context.root = root;+ onTestFailed(() => console.error(`❌ database transfer fixture failed: ${diagnostics()}`));journal = createDatabaseMaintenanceJournal(join(root, 'data'));stubs = installDatabaseStubs(root);strays = [];+ ordinary = [];+ context.timed = (name, run) => stubs.timed(name, run);rows = [{ name: 'portos-cos', pmId: 12, pid: 1012, status: 'online', cwd: root, script: 'server/cos-runner/index.js' },{ name: 'portos-server', pmId: 13, pid: 1013, status: 'online', cwd: root, script: 'server/start.js' },];- context.list = vi.fn(async () => rows.map(row => ({ ...row })));- context.stop = vi.fn(async id => {+ context.list = vi.fn(() => stubs.timed('listMaintenanceProcesses', async () => rows.map(row => ({ ...row }))));+ context.stop = vi.fn(id => stubs.timed('stopApp', async () => {const row = rows.find(value => value.pmId === id);stubs.event('stop ' + row.name);row.status = 'stopped'; row.pid = 0;return { success: true };- });+ }));// Inherited libpq settings that must never redirect the transfer.Object.assign(process.env, {PATH: `${stubs.bin}:${savedEnv.PATH}`, PGPASSWORD: 'example-password',@@ -74,12 +85,20 @@ beforeEach(() => {PGOPTIONS: '-c search_path=inherited',});});-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 group of strays) { try { process.kill(-group, 'SIGKILL'); } catch { /* already gone */ } }+ for (const child of ordinary) child.kill('SIGKILL');+ // A timed-out case's transfer is still running: end the stubs it waits on and+ // let it settle BEFORE its root goes, so it neither overlaps the next case+ // nor writes into a removed root. Never infer completion from the timeout:+ // while anything is in flight, keep the root and say so.+ const contained = await stubs.contain();+ if (process.env.DB_TRANSFER_DIAG) console.log(`⏱️ database transfer fixture: ${stubs.report()}`);context.root = undefined;- rmSync(root, { recursive: true, force: true });+ if (contained) rmSync(root, { recursive: true, force: true });+ else console.error(`❌ database transfer fixture still in flight at teardown; keeping its disposable root: ${stubs.report()}`);});function begin(source = native, target = docker) {@@ -97,7 +116,14 @@ function successor() {return previous;}-const transfer = () => runDatabaseTransfer(operation.id, token, fast);+// Last harness phase plus owned-child state, for a failure or timeout. Bounded+// and redacted: mark names, child kinds and durations only.+const diagnostics = () => {+ let stage = 'unknown';+ try { stage = journal.read()?.stage ?? 'none'; } catch { /* journal not readable */ }+ return stubs.report(`stage=${stage}`);+};+const transfer = () => stubs.track(stubs.timed('runDatabaseTransfer', () => runDatabaseTransfer(operation.id, token, fast)));const dumpPath = () => join(root, 'data', 'db-dumps', `portos-maintenance-${operation.id}.sql`);// An ordinary process of this install: a pooled write and a detached spawn.@@ -118,6 +144,7 @@ function ordinaryWriter() {delete env.VITEST;return new Promise((resolve, reject) => {const child = spawn(process.execPath, ['--input-type=module', '-e', code], { env, stdio: ['ignore', 'pipe', 'pipe'] });+ ordinary.push(child);let stdout = '';child.stdout.on('data', chunk => { stdout += chunk; });child.once('error', reject);@@ -197,6 +224,30 @@ describe.skipIf(process.platform === 'win32')('offline database transfer', () =>expect(await pending).toMatchObject({ importCommitted: true });}, 30_000);+ // Regression caught: a case that times out while a stub is blocked leaves its+ // transfer and child running into the next case, or writing into a removed root.+ it('reports a blocked case\'s last phase and owned child state, then settles it before its root goes', async () => {+ begin();+ stubs.setMode('dump', 'pause');+ const pending = transfer();+ const outcome = pending.then(() => 'resolved', error => error.message);+ await vi.waitFor(() => expect(stubs.started('dump')).toBe(true), { timeout: 10_000, interval: 20 });++ const blocked = diagnostics();+ expect(blocked).toMatch(/^last=\S+\(\d+ms ago\) slowest=.+ children=dump:running pending=1 stage=exporting$/);+ expect(blocked).toMatch(/snapshotProcesses=\d+x\/\d+ms/);+ // No argv, endpoint, credential or path reaches the report (the only "/" is a count/duration separator).+ expect(blocked).not.toMatch(/invalid|example|portos|bash|db\.sh|pg_dump|psql|PG[A-Z]|\/(?!\d)/);++ expect(await stubs.contain()).toBe(true);+ expect(await outcome).toMatch(/source export failed/);+ // SIGKILL skips the stub's own exit line, so a contained child reads gone, not exited.+ expect(diagnostics()).toMatch(/children=dump:gone pending=0 stage=exporting$/);+ // Nothing continued past the settled case: no import began, no dump recorded.+ expect(stubs.invocations('psql')).toEqual([]);+ expect(journal.transferStatus(operation.id)).toEqual({ dump: 'absent', import: 'pending' });+ }, 30_000);+it.each(['fail', 'incomplete'])('never records a %s export; a recovered owner re-quiesces and exports again', async mode => {begin();stubs.setMode('dump', mode);@@ -206,7 +257,7 @@ describe.skipIf(process.platform === 'win32')('offline database transfer', () =>expect(stubs.invocations('psql')).toEqual([]);const retired = successor();- await expect(runDatabaseTransfer(operation.id, retired, fast)).rejects.toThrow();+ await expect(stubs.track(runDatabaseTransfer(operation.id, retired, fast))).rejects.toThrow();stubs.setMode('dump', 'ok');const listed = context.list.mock.calls.length;expect(await transfer()).toMatchObject({ stage: 'importing', imported: true });diff --git a/server/test/fixtures/databaseTransferStubs.js b/server/test/fixtures/databaseTransferStubs.jsindex bbb0047d65..7641533852 100644--- a/server/test/fixtures/databaseTransferStubs.js+++ b/server/test/fixtures/databaseTransferStubs.js@@ -8,12 +8,25 @@// is switched by mode files: dump-mode (ok | fail | incomplete | pause) and// import-mode (ok | fail | pause). A paused stub publishes `<kind>-started`// and waits for `<kind>-release`. events.log orders stops, dumps and imports.+//+// The fixture also OWNS what it starts. Each stub registers its pid and logs+// start/exit in phases.log (pid, kind and event only: never argv, environment+// or paths), and the harness records timed marks for its own awaits. That is+// the whole of `report()`, so a stalled case names its last phase and child+// state without exposing command lines or credentials, and `contain()` is what+// a teardown calls to stop the stubs and wait out the in-flight transfer before+// the disposable root is removed.import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { join } from 'node:path';+import { isProcessAlive } from '../processAlive.js';export const STUB_DUMP_BODY = 'CREATE TABLE example_record (id int);\n';export const STUB_DUMP_COMPLETE = `${STUB_DUMP_BODY}--\n-- PostgreSQL database dump complete\n--\n\n`;+const POLL_MS = 20;+const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));+const MAX_MARKS = 200;+const quote = value => `'${value.replaceAll("'", "'\\''")}'`;function writeStub(path, body) {@@ -27,12 +40,15 @@ export function installDatabaseStubs(root) {mkdirSync(bin, { recursive: true });const R = quote(dir);const logInvocation = name => `{ echo "${name} $*"; env | grep '^PG' | sort | sed 's/^/env /'; } >> "$R/calls.log"`;+ const phase = (kind, event) => `echo "$$ ${kind} ${event} $(date +%s)" >> "$R/phases.log"`;const pause = kind => `: > "$R/${kind}-started"; while [ ! -e "$R/${kind}-release" ]; do sleep 0.05; done`;writeStub(join(bin, 'uname'), '#!/bin/sh\necho Linux\n');writeStub(join(bin, 'pg_dump'), `#!/bin/shR=${R}mode=$(cat "$R/dump-mode" 2>/dev/null || echo ok)${logInvocation('pg_dump')}+${phase('dump', 'start')}+trap '${phase('dump', 'exit')}' EXITwriter=noneif [ -s "$R/writer.pid" ]; thenif kill -0 "$(cat "$R/writer.pid")" 2>/dev/null; then writer=alive; else writer=dead; fi@@ -50,6 +66,8 @@ R=${R}case "$*" in *--single-transaction*) ;; *) echo "psql-other $*" >> "$R/calls.log"; exit 0 ;; esacmode=$(cat "$R/import-mode" 2>/dev/null || echo ok)${logInvocation('psql')}+${phase('import', 'start')}+trap '${phase('import', 'exit')}' EXITecho "import-start" >> "$R/events.log"if [ "$mode" = pause ]; then ${pause('import')}; ficat > "$R/import.pending"@@ -58,6 +76,45 @@ mv "$R/import.pending" "$R/imported.sql"echo "import-commit" >> "$R/events.log"`);const read = name => (existsSync(join(dir, name)) ? readFileSync(join(dir, name), 'utf8') : '');++ // Stub children by pid, from their own start/exit lines: { pid, kind, running }.+ const children = () => {+ const byPid = new Map();+ for (const line of read('phases.log').split('\n').filter(Boolean)) {+ const [pid, kind, event] = line.split(' ');+ byPid.set(Number(pid), { pid: Number(pid), kind, running: event === 'start' });+ }+ return [...byPid.values()];+ };+ const marks = [];+ const pending = new Set();+ const mark = (name, ms = null) => {+ marks.push({ name, ms, at: Date.now() });+ if (marks.length > MAX_MARKS) marks.shift();+ };+ const timed = async (name, run) => {+ const began = Date.now();+ mark(name + ':begin');+ try { return await run(); } finally { mark(name + ':end', Date.now() - began); }+ };+ // One line, bounded: mark names the harness chose, child kind/state, and+ // durations. Nothing read from the stubs' argv, environment or paths.+ const report = (extra = '') => {+ const last = marks.at(-1);+ const totals = new Map();+ for (const entry of marks.filter(value => value.ms !== null)) {+ const name = entry.name.replace(/:end$/, '');+ const total = totals.get(name) ?? { count: 0, ms: 0, max: 0 };+ totals.set(name, { count: total.count + 1, ms: total.ms + entry.ms, max: Math.max(total.max, entry.ms) });+ }+ const slow = [...totals].sort((x, y) => y[1].ms - x[1].ms).slice(0, 4)+ .map(([name, total]) => `${name}=${total.count}x/${total.ms}ms(max ${total.max}ms)`);+ const states = children().map(child => `${child.kind}:${child.running ? (isProcessAlive(child.pid) ? 'running' : 'gone') : 'exited'}`);+ return [`last=${last ? `${last.name}(${Date.now() - last.at}ms ago)` : 'none'}`,+ `slowest=${slow.join(',') || 'none'}`, `children=${states.join(',') || 'none'}`,+ `pending=${pending.size}`, extra].filter(Boolean).join(' ');+ };+return {dir,bin,@@ -74,5 +131,29 @@ echo "import-commit" >> "$R/events.log"receivedVariables: () => [...new Set(read('calls.log').split('\n').filter(line => line.startsWith('env ')).map(line => line.slice(4).split('=')[0]))].sort(),writerPid: pid => writeFileSync(join(dir, 'writer.pid'), String(pid)),+ timed,+ report,+ // The in-flight workflow promise a case started. A timed-out case's+ // transfer keeps running unless contain() settles it.+ track: promise => {+ const entry = promise.then(() => {}, () => {}).finally(() => pending.delete(entry));+ pending.add(entry);+ return promise;+ },+ // Teardown: SIGKILL only the stubs this fixture's own phases.log says are+ // still running, wait until each is gone, then wait (bounded) for tracked+ // workflows to settle. A killed stub fails its export/import, which is how+ // an otherwise uncancellable await chain ends. Returns false when something+ // is still in flight, so the caller keeps the root rather than letting it+ // write into a removed one. A timeout is never taken as completion.+ contain: async ({ settleMs = 15_000 } = {}) => {+ const deadline = Date.now() + settleMs;+ const owned = () => children().filter(child => child.running && isProcessAlive(child.pid));+ while (Date.now() < deadline && (owned().length > 0 || pending.size > 0)) {+ for (const child of owned()) { try { process.kill(child.pid, 'SIGKILL'); } catch { /* already gone */ } }+ await sleep(POLL_MS);+ }+ return owned().length === 0 && pending.size === 0;+ },};}