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: diagnose Windows detached job startup failures (#8578)

[._.]/ Adam Eivy0a7fc807f29f
diff --git a/server/lib/detachedSpawn.bootstrap.test.js b/server/lib/detachedSpawn.bootstrap.test.js
new file mode 100644
index 0000000000..8dfba8202e
--- /dev/null
+++ b/server/lib/detachedSpawn.bootstrap.test.js
@@ -0,0 +1,81 @@
+import { EventEmitter } from 'events';
+import { mkdtemp, readFile, rm, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { spawn } from './childProcess.js';
+import { pinPlatform } from './testHelper.js';
+import { spawnDetached } from './detachedSpawn.js';
+
+vi.mock('./childProcess.js', async (original) => ({
+ ...(await original()),
+ spawn: vi.fn(),
+}));
+
+let controlDir;
+let restorePlatform;
+beforeEach(async () => {
+ controlDir = await mkdtemp(join(tmpdir(), 'bootstrap-test-'));
+ restorePlatform = pinPlatform('win32');
+});
+afterEach(async () => {
+ restorePlatform();
+ vi.restoreAllMocks();
+ await rm(controlDir, { recursive: true, force: true });
+});
+
+function launcher(run) {
+ spawn.mockImplementation(() => {
+ const child = new EventEmitter();
+ child.unref = vi.fn();
+ setImmediate(() => run(child));
+ return child;
+ });
+}
+const failure = (handle) => new Promise((resolve) => handle.once('error', resolve));
+
+describe('Windows detached bootstrap failure contract', () => {
+ it('retains bounded diagnostics in the error before cleanup removes the files', async () => {
+ launcher(async (child) => {
+ await writeFile(join(controlDir, 'launcher-bootstrap.log'), 'supervisor-started hresult=0');
+ await writeFile(join(controlDir, 'supervisor-bootstrap.log'), 'failed hresult=-2147024894');
+ await writeFile(join(controlDir, 'exit'), '1');
+ child.emit('exit', 0);
+ });
+ const handle = await spawnDetached('example-job', [], { controlDir, pollMs: 1, cleanup: true });
+ const error = await failure(handle);
+ expect(handle.pid).toBeNull();
+ expect(error.message).toContain('launcher=0');
+ expect(error.message).toContain('supervisor-stage=failed hresult=-2147024894');
+ await vi.waitFor(async () => {
+ await expect(readFile(join(controlDir, 'supervisor-bootstrap.log'))).rejects.toThrow();
+ });
+ });
+
+ it('reports a launcher spawn error without copying paths or environment data', async () => {
+ launcher((child) => child.emit('error', Object.assign(
+ new Error('secret-value C:\\Users\\example-user\\private'), { code: 'ENOENT' }
+ )));
+ const handle = await spawnDetached('example-job', [], { controlDir, pollMs: 1 });
+ const error = await failure(handle);
+ expect(error.message).toContain('launcher=ENOENT');
+ expect(error.message).not.toMatch(/secret-value|example-user/);
+ expect(await readFile(join(controlDir, 'launcher-result.log'), 'utf8')).toBe('ENOENT');
+ expect(await readFile(join(controlDir, 'launch-cancelled'), 'utf8')).toBe('1');
+ });
+
+ it('keeps a missing PID an error and rejects arbitrary bootstrap text', async () => {
+ launcher(async (child) => {
+ await writeFile(join(controlDir, 'supervisor-bootstrap.log'), 'secret-value '.repeat(1000));
+ child.emit('exit', 1);
+ });
+ const handle = await spawnDetached('example-job', [], { controlDir, pollMs: 1, pidTimeoutMs: 50 });
+ const error = await failure(handle);
+ expect(error.message).toContain('within 50ms');
+ expect(error.message).toContain('launcher=1');
+ expect(error.message).toContain('supervisor-stage=invalid');
+ expect(error.message).not.toContain('secret-value');
+ expect(error.message.length).toBeLessThan(300);
+ expect(await readFile(join(controlDir, 'launch-cancelled'), 'utf8')).toBe('1');
+ });
+});
diff --git a/server/lib/detachedSpawn.js b/server/lib/detachedSpawn.js
index a093379cd6..741e5c5a64 100644
--- a/server/lib/detachedSpawn.js
+++ b/server/lib/detachedSpawn.js
@@ -248,14 +248,26 @@ d="$1"; shift
// the job lives, so a throw AFTER a successful launch (a faulting
// `WaitForExit`, a sharing violation on the pid write) would fail on its own
// error write and never reach the sentinel — leaving the tailer polling
-// forever, `executeUpdate`'s promise unsettled, and the update lock wedged
-// until its 30-minute stale timeout. Before the launch nothing holds the log,
-// so a launch failure is reported there where the caller's stderr stream sees
-// it; after it, the error goes to a file of its own.
+// forever. Bootstrap diagnostics use their own file, independent of those
+// locks, and never include raw exception text.
+// Only fixed stage names and numeric HRESULTs reach diagnostics. PowerShell
+// exception text can embed commands, credentials and user-specific paths.
+const WINDOWS_BOOTSTRAP_DIAGNOSTIC = `
+function Write-BootstrapStage($stage, $errorCode = 0) {
+ [System.IO.File]::WriteAllText($diagnosticFile, "$stage hresult=$errorCode")
+}
+`;
+
const WINDOWS_SUPERVISOR = `$dir = Split-Path -Parent $MyInvocation.MyCommand.Path
+$diagnosticFile = Join-Path $dir 'supervisor-bootstrap.log'
+${WINDOWS_BOOTSTRAP_DIAGNOSTIC}
$started = $false
+function Test-LaunchCancelled {
+ return (!(Test-Path -LiteralPath $dir) -or (Test-Path -LiteralPath (Join-Path $dir 'launch-cancelled')))
+}
try {
$ErrorActionPreference = 'Stop'
+ Write-BootstrapStage 'reading-job'
$job = Get-Content -LiteralPath (Join-Path $dir 'job.json') -Raw -Encoding UTF8 | ConvertFrom-Json
$params = @{
FilePath = $job.bin
@@ -266,10 +278,24 @@ try {
}
if ($job.arguments) { $params.ArgumentList = $job.arguments }
if ($job.cwd) { $params.WorkingDirectory = $job.cwd }
+ if (Test-LaunchCancelled) {
+ Write-BootstrapStage 'cancelled'
+ [System.IO.File]::WriteAllText((Join-Path $dir 'exit'), '1')
+ exit 1
+ }
+ Write-BootstrapStage 'starting-job'
$p = Start-Process @params
$started = $true
$null = $p.Handle
[System.IO.File]::WriteAllText((Join-Path $dir 'pid'), "$($p.Id)")
+ Write-BootstrapStage 'pid-written'
+ # A timed-out caller can remove its control directory before this cold
+ # supervisor starts. Check throughout the handoff so late children are reaped.
+ while (!$p.WaitForExit(250)) {
+ if (Test-LaunchCancelled) {
+ & taskkill /pid $p.Id /T /F 2>$null | Out-Null
+ }
+ }
$p.WaitForExit()
# ExitCode is a SIGNED int, so a status at or above 0x80000000 (0xC0000005 and
# the rest of the NTSTATUS crash codes) reads back negative. Node's own
@@ -281,9 +307,12 @@ try {
$code = [int64]$p.ExitCode -band 0xFFFFFFFFL
[System.IO.File]::WriteAllText((Join-Path $dir 'exit'), "$code")
} catch {
- $errFile = if ($started) { 'supervisor-error.log' } else { 'stderr.log' }
- try { [System.IO.File]::WriteAllText((Join-Path $dir $errFile), $_.Exception.ToString()) } catch { }
- [System.IO.File]::WriteAllText((Join-Path $dir 'exit'), '1')
+ $failureCode = $_.Exception.HResult
+ try { Write-BootstrapStage 'failed' $failureCode } catch { }
+ try {
+ if ($started -and !$p.HasExited) { & taskkill /pid $p.Id /T /F 2>$null | Out-Null }
+ } catch { }
+ try { [System.IO.File]::WriteAllText((Join-Path $dir 'exit'), '1') } catch { }
}
`;
@@ -322,12 +351,19 @@ async function launchWindowsSupervisor({ controlDir, bin, args, env, cwd }) {
]);
const supervisorArgs = `-NoProfile -NonInteractive -ExecutionPolicy Bypass -File ${quoteWindowsArg(supervisorPath)}`;
const startSupervisor = [
+ '$ErrorActionPreference = "Stop";',
+ `$diagnosticFile = ${quoteForShell(join(controlDir, 'launcher-bootstrap.log'), 'powershell')};`,
+ WINDOWS_BOOTSTRAP_DIAGNOSTIC,
+ 'try {',
+ "Write-BootstrapStage 'starting-supervisor';",
'$psi = New-Object System.Diagnostics.ProcessStartInfo;',
"$psi.FileName = 'powershell';",
`$psi.Arguments = ${quoteForShell(supervisorArgs, 'powershell')};`,
'$psi.UseShellExecute = $false;',
'$psi.CreateNoWindow = $true;',
- '[void][System.Diagnostics.Process]::Start($psi)',
+ '[void][System.Diagnostics.Process]::Start($psi);',
+ "Write-BootstrapStage 'supervisor-started';",
+ "} catch { try { Write-BootstrapStage 'failed' $_.Exception.HResult } catch { }; exit 1 }",
].join(' ');
return spawn('powershell', [
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', startSupervisor,
@@ -340,6 +376,24 @@ async function launchWindowsSupervisor({ controlDir, bin, args, env, cwd }) {
});
}
+// Read a bounded projection even if a corrupt control file contains arbitrary
+// text. Never include raw PowerShell output or exception messages in an error.
+async function readBootstrapDiagnostic(controlDir, name) {
+ const file = await open(join(controlDir, name), 'r').catch(() => null);
+ if (!file) return 'unavailable';
+ try {
+ const buffer = Buffer.alloc(256);
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
+ const value = buffer.subarray(0, bytesRead).toString('utf8');
+ return /^(starting-supervisor|supervisor-started|reading-job|starting-job|pid-written|failed|cancelled) hresult=-?\d{1,11}$/.test(value)
+ ? value : 'invalid';
+ } catch {
+ return 'unreadable';
+ } finally {
+ await file.close().catch(() => {});
+ }
+}
+
/**
* Build the log-tailer for a spawnDetached control dir. Holds a persistent fd
* per log (opened lazily once the supervisor creates the file) plus the byte
@@ -507,7 +561,8 @@ export async function spawnDetached(bin, args = [], {
// would bypass that and strand a `running` run or leak temp files. Deferred
// so the listener is attached before it fires.
const ensureControlDir = await ensureDir(controlDir).then(
- () => Promise.all([pidFile, exitFile, stdoutLog, stderrLog, groupKillFile].map((f) => rm(f, { force: true }))),
+ () => Promise.all([pidFile, exitFile, stdoutLog, stderrLog, groupKillFile,
+ ...(isWindows ? ['launcher-bootstrap.log', 'supervisor-bootstrap.log', 'launcher-result.log', 'launch-cancelled'].map((name) => join(controlDir, name)) : [])].map((f) => rm(f, { force: true }))),
).then(
() => (killProcessGroup ? writeFile(groupKillFile, '1') : null),
).then(() => null, (err) => err);
@@ -532,6 +587,7 @@ export async function spawnDetached(bin, args = [], {
// too; route that into the same slot rather than letting it reject
// spawnDetached, for the reason ensureControlDir above spells out.
let launcherSpawnError = null;
+ let launcherExit = null;
const launcher = isWindows
? await launchWindowsSupervisor({ controlDir, bin, args, env, cwd })
.catch((err) => { launcherSpawnError = err; return null; })
@@ -543,6 +599,7 @@ export async function spawnDetached(bin, args = [], {
stdio: 'ignore',
});
launcher?.on('error', (err) => { launcherSpawnError = err; });
+ launcher?.on('exit', (code) => { launcherExit = Number.isInteger(code) ? code : 'signal'; });
launcher?.unref();
// Tail the on-disk log files and watch for the supervisor's exit sentinel,
@@ -574,19 +631,45 @@ export async function spawnDetached(bin, args = [], {
handle.pid = pid;
return;
}
+ if (isWindows && (await readFile(exitFile, 'utf8').catch(() => '')).length > 0) {
+ // A fast job can publish both files between these reads.
+ const completedPid = Number.parseInt(await readFile(pidFile, 'utf8').catch(() => ''), 10);
+ if (Number.isFinite(completedPid) && completedPid > 0) {
+ handle.pid = completedPid;
+ return;
+ }
+ launchError = new Error('Windows supervisor exited before recording a PID');
+ return;
+ }
await sleep(pollMs);
}
// No PID. If the supervisor still recorded an exit status, the job ran and
// exited (e.g. a non-existent bin → 127); route that through 'close'.
// Otherwise it's a hard launch failure.
const exitRaw = await readFile(exitFile, 'utf8').catch(() => '');
- if (exitRaw.length === 0) {
+ if (exitRaw.length === 0 || isWindows) {
launchError = new Error(`detached spawn produced no PID within ${pidTimeoutMs}ms`);
}
};
await awaitPid();
+ if (isWindows && launchError) {
+ // Persist cancellation before returning or scheduling cleanup. A supervisor
+ // still cold-starting must not launch an orphan after this failed handoff.
+ await writeFile(join(controlDir, 'launch-cancelled'), '1').catch(() => {});
+ const launcherResult = launcherSpawnError
+ ? (['ENOENT', 'EACCES', 'EPERM', 'EAGAIN', 'ENOMEM'].includes(launcherSpawnError.code)
+ ? launcherSpawnError.code : 'spawn-error')
+ : (launcherExit === null ? 'pending' : String(launcherExit));
+ await writeFile(join(controlDir, 'launcher-result.log'), launcherResult).catch(() => {});
+ const [launcherStage, supervisorStage] = await Promise.all([
+ readBootstrapDiagnostic(controlDir, 'launcher-bootstrap.log'),
+ readBootstrapDiagnostic(controlDir, 'supervisor-bootstrap.log'),
+ ]);
+ launchError = new Error(`detached spawn failed to acquire PID within ${pidTimeoutMs}ms; launcher=${launcherResult}; launcher-stage=${launcherStage}; supervisor-stage=${supervisorStage}`);
+ }
+
// Kick off tailing (or the launch-failure path) AFTER returning, so the
// caller's synchronous event listeners are wired first.
setImmediate(() => {
diff --git a/server/lib/detachedSpawn.test.js b/server/lib/detachedSpawn.test.js
index 564e75a673..7697e5d62f 100644
--- a/server/lib/detachedSpawn.test.js
+++ b/server/lib/detachedSpawn.test.js
@@ -150,7 +150,9 @@ const readStdoutLog = (controlDir) => readFile(join(controlDir, 'stdout.log'), '
const blockUntil = (marker) => `while [ ! -f "${marker}" ]; do sleep 0.02; done`;
describe('spawnDetached', () => {
- it('streams stdout and stderr, then closes with the exit code', async () => {
+ // Independent launches, never retries: each cold launcher must satisfy all
+ // stream and exit assertions. Windows CI exercises the handoff three times.
+ it.each(IS_POSIX ? [1] : [1, 2, 3])('streams stdout and stderr, then closes with the exit code (launch %i)', async () => {
const controlDir = await tmpControlDir();
// Windows CI runners occasionally take longer than the 10s production
// default to spin up the launcher/supervisor powershell chain on a cold,
@@ -158,8 +160,8 @@ describe('spawnDetached', () => {
// that startup cost. Give it CI headroom without touching the
// production timeout.
const handle = await spawnDetached(
- 'sh',
- ['-c', 'printf "out-a\\nout-b\\n"; printf "err-1\\n" 1>&2; exit 0'],
+ process.execPath,
+ ['-e', 'process.stdout.write("out-a\\nout-b\\n"); process.stderr.write("err-1\\n");'],
{ controlDir, pollMs: 25, pidTimeoutMs: 30000 }
);
const getOut = collect(handle.stdout);
@@ -321,6 +323,27 @@ describe('spawnDetached', () => {
expect(getOut()).toBe('a b "c"\n');
});
+ it.runIf(!IS_POSIX)('reports a real supervisor bootstrap failure without private paths', async () => {
+ const controlDir = await tmpControlDir();
+ const handle = await spawnDetached('portos-nonexistent-example-command', [], { controlDir });
+ await expect(onClose(handle)).rejects.toThrow(/supervisor-stage=failed hresult=-?\d+/);
+ expect(await readFile(join(controlDir, 'supervisor-bootstrap.log'), 'utf8')).toMatch(/^failed hresult=-?\d+$/);
+ });
+
+ it.runIf(!IS_POSIX)('cancels a cold supervisor after PID acquisition times out', async () => {
+ const controlDir = await tmpControlDir();
+ const handle = await spawnDetached(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], {
+ controlDir, pidTimeoutMs: 0,
+ });
+ await expect(onClose(handle)).rejects.toThrow(/failed to acquire PID/);
+ // Wait for the actual supervisor acknowledgement, not a guessed sleep.
+ expect(await waitUntil(async () => (
+ await readFile(join(controlDir, 'exit'), 'utf8').catch(() => '')
+ ).length > 0, { timeoutMs: 30000 })).toBe(true);
+ const pid = Number.parseInt(await readFile(join(controlDir, 'pid'), 'utf8').catch(() => ''), 10);
+ expect(Number.isFinite(pid) && isAliveForTest(pid)).toBe(false);
+ }, 45000);
+
// The whole POINT of the Windows launcher: pm2 kills on Windows with
// `taskkill /pid <app> /T /F`, which walks the parent tree, so a job spawned
// as a plain child of portos-server dies at update.sh's own `pm2-stop` step