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

[issue-8578] Preserve Windows detached bootstrap stage timings (#9553)

[._.]/cf99df1f5e0e
diff --git a/server/lib/detachedSpawn.bootstrap.test.js b/server/lib/detachedSpawn.bootstrap.test.js
index 526882862d..5c131f865b 100644
--- a/server/lib/detachedSpawn.bootstrap.test.js
+++ b/server/lib/detachedSpawn.bootstrap.test.js
@@ -10,7 +10,7 @@ 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';
+import { spawnDetached, __detachedSpawnTesting } from './detachedSpawn.js';
vi.mock('./childProcess.js', async (original) => ({
...(await original()),
@@ -43,7 +43,12 @@ 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, 'supervisor-bootstrap.log'), [
+ 'reading-job hresult=0 elapsed-ms=820',
+ 'starting-job hresult=0 elapsed-ms=900',
+ 'failed hresult=-2147024894 elapsed-ms=9401',
+ '',
+ ].join('\n'));
await writeFile(join(controlDir, 'exit'), '1');
child.emit('exit', 0);
});
@@ -52,11 +57,41 @@ describe('Windows detached bootstrap failure contract', () => {
expect(handle.pid).toBeNull();
expect(error.message).toContain('launcher=0');
expect(error.message).toContain('supervisor-stage=failed hresult=-2147024894');
+ expect(error.message).toContain('elapsed-ms=9401; timeline=reading-job@820ms>starting-job@900ms>failed@9401ms');
await vi.waitFor(async () => {
await expect(readFile(join(controlDir, 'supervisor-bootstrap.log'))).rejects.toThrow();
});
});
+ it('projects successful handoff timings without exporting absolute timestamps or job data', async () => {
+ const rows = [
+ 'reading-job hresult=0 elapsed-ms=700',
+ 'starting-job hresult=0 elapsed-ms=750',
+ 'job-started hresult=0 elapsed-ms=1400',
+ 'handle-acquired hresult=0 elapsed-ms=1401',
+ 'pid-written hresult=0 elapsed-ms=1403',
+ ];
+ await writeFile(join(controlDir, 'supervisor-bootstrap.log'), rows.join('\r\n') + '\r\n');
+ expect(await __detachedSpawnTesting.readBootstrapDiagnostic(controlDir, 'supervisor-bootstrap.log'))
+ .toBe('pid-written hresult=0 elapsed-ms=1403; timeline=reading-job@700ms>starting-job@750ms>job-started@1400ms>handle-acquired@1401ms>pid-written@1403ms');
+ // Retained control directories from older launches still have one row.
+ await writeFile(join(controlDir, 'supervisor-bootstrap.log'), 'pid-written hresult=0');
+ expect(await __detachedSpawnTesting.readBootstrapDiagnostic(controlDir, 'supervisor-bootstrap.log'))
+ .toBe('pid-written hresult=0');
+ });
+
+ it.each([
+ ['private trailing text', 'pid-written hresult=0 elapsed-ms=10\nsecret-value'],
+ ['oversized valid prefix', 'pid-written hresult=0 elapsed-ms=10\n'.repeat(40) + 'secret-value'],
+ ['excess stage count', 'pid-written hresult=0 elapsed-ms=10\n'.repeat(7)],
+ ['unbounded timing', 'pid-written hresult=0 elapsed-ms=12345678901234'],
+ ['unknown stage', 'secret-value hresult=0 elapsed-ms=10'],
+ ])('rejects %s before successful-launch diagnostics can be logged', async (_name, value) => {
+ await writeFile(join(controlDir, 'supervisor-bootstrap.log'), value);
+ expect(await __detachedSpawnTesting.readBootstrapDiagnostic(controlDir, 'supervisor-bootstrap.log'))
+ .toBe('invalid');
+ });
+
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' }
diff --git a/server/lib/detachedSpawn.js b/server/lib/detachedSpawn.js
index 15fc6274a5..61df6d41dd 100644
--- a/server/lib/detachedSpawn.js
+++ b/server/lib/detachedSpawn.js
@@ -251,15 +251,20 @@ d="$1"; shift
// error write and never reach the sentinel — leaving the tailer polling
// 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.
+// Only fixed stage names, numeric HRESULTs and elapsed milliseconds reach
+// diagnostics. The launcher and supervisor share a wall-clock origin so a late
+// supervisor can be distinguished from time spent inside Start-Process. Keep
+// the short history on success too; a last-stage label alone loses that timing.
+// PowerShell exception text can embed commands, credentials and private paths.
const WINDOWS_BOOTSTRAP_DIAGNOSTIC = `
-function Write-BootstrapStage($stage, $errorCode = 0) {
- [System.IO.File]::WriteAllText($diagnosticFile, "$stage hresult=$errorCode")
+function Write-BootstrapStage($stage, $errorCode = 0, $elapsedMs = $null) {
+ if ($null -eq $elapsedMs) { $elapsedMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $bootstrapStartedAt }
+ [System.IO.File]::AppendAllText($diagnosticFile, "$stage hresult=$errorCode elapsed-ms=$elapsedMs\`n")
}
`;
-const WINDOWS_SUPERVISOR = `$dir = Split-Path -Parent $MyInvocation.MyCommand.Path
+const WINDOWS_SUPERVISOR = `param([long]$bootstrapStartedAt)
+$dir = Split-Path -Parent $MyInvocation.MyCommand.Path
$diagnosticFile = Join-Path $dir 'supervisor-bootstrap.log'
${WINDOWS_BOOTSTRAP_DIAGNOSTIC}
$started = $false
@@ -287,7 +292,13 @@ try {
Write-BootstrapStage 'starting-job'
$p = Start-Process @params
$started = $true
+ $jobStartedMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $bootstrapStartedAt
+ # Cache the process handle before any diagnostic file I/O: a short job can
+ # exit while that I/O runs, but we must retain its exit-code contract.
$null = $p.Handle
+ $handleAcquiredMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() - $bootstrapStartedAt
+ Write-BootstrapStage 'job-started' 0 $jobStartedMs
+ Write-BootstrapStage 'handle-acquired' 0 $handleAcquiredMs
[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
@@ -350,9 +361,11 @@ async function launchWindowsSupervisor({ controlDir, bin, args, env, cwd }) {
}), 'utf8'),
writeFile(supervisorPath, WINDOWS_SUPERVISOR, 'utf8'),
]);
- const supervisorArgs = `-NoProfile -NonInteractive -ExecutionPolicy Bypass -File ${quoteWindowsArg(supervisorPath)}`;
+ const bootstrapStartedAt = Date.now();
+ const supervisorArgs = `-NoProfile -NonInteractive -ExecutionPolicy Bypass -File ${quoteWindowsArg(supervisorPath)} -bootstrapStartedAt ${bootstrapStartedAt}`;
const startSupervisor = [
'$ErrorActionPreference = "Stop";',
+ `$bootstrapStartedAt = ${bootstrapStartedAt};`,
`$diagnosticFile = ${quoteForShell(join(controlDir, 'launcher-bootstrap.log'), 'powershell')};`,
WINDOWS_BOOTSTRAP_DIAGNOSTIC,
'try {',
@@ -383,11 +396,22 @@ 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);
+ // One launcher writes at most three rows; one supervisor at most six.
+ // Read an extra byte so a valid prefix cannot conceal an oversized tail.
+ const buffer = Buffer.alloc(1025);
const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
+ if (bytesRead > 1024) return 'invalid';
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';
+ const rows = value.replace(/\r?\n$/, '').split(/\r?\n/);
+ const pattern = /^(starting-supervisor|supervisor-started|reading-job|starting-job|job-started|handle-acquired|pid-written|failed|cancelled) hresult=-?\d{1,11}(?: elapsed-ms=(-?\d{1,13}))?$/;
+ if (rows.length > 6 || !rows.every((row) => pattern.test(row))) return 'invalid';
+ // A single legacy stage/HRESULT row remains readable. Only allowlisted
+ // stage names and relative times are projected from the earlier rows.
+ const timeline = rows.map((row) => {
+ const [, stage, elapsed] = pattern.exec(row);
+ return elapsed === undefined ? stage : `${stage}@${elapsed}ms`;
+ });
+ return rows.at(-1) + (rows.length > 1 ? `; timeline=${timeline.join('>')}` : '');
} catch {
return 'unreadable';
} finally {
@@ -1006,7 +1030,7 @@ const processMatches = async (pid, expectedProcess) => {
return processCommandMatches(command, expectedProcess);
};
-export const __detachedSpawnTesting = { processCommandMatches };
+export const __detachedSpawnTesting = { processCommandMatches, readBootstrapDiagnostic };
export async function isDetachedRunning(controlDir, expectedProcess = null) {
const pidRaw = await readControlFile(join(controlDir, 'pid'));
diff --git a/server/lib/detachedSpawn.test.js b/server/lib/detachedSpawn.test.js
index ecca757613..281d390f07 100644
--- a/server/lib/detachedSpawn.test.js
+++ b/server/lib/detachedSpawn.test.js
@@ -158,7 +158,7 @@ const blockUntil = (marker) => `while [ ! -f "${marker}" ]; do sleep 0.02; done`
describe('spawnDetached', () => {
// 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 () => {
+ it.each(IS_POSIX ? [1] : [1, 2, 3])('streams stdout and stderr, then closes with the exit code (launch %i)', async (launch) => {
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,
@@ -178,6 +178,14 @@ describe('spawnDetached', () => {
expect(getOut()).toBe('out-a\nout-b\n');
expect(getErr()).toBe('err-1\n');
expect(handle.exitCode).toBe(0);
+ if (!IS_POSIX) {
+ const diagnostic = await __detachedSpawnTesting.readBootstrapDiagnostic(controlDir, 'supervisor-bootstrap.log');
+ expect(diagnostic).toMatch(/^pid-written hresult=0 elapsed-ms=\d+; timeline=reading-job@\d+ms>starting-job@\d+ms>job-started@\d+ms>handle-acquired@\d+ms>pid-written@\d+ms$/);
+ // Keep passing-run evidence too, using the same bounded projection as
+ // production failures. CI's quiet setup replaces console methods, so
+ // write this bounded evidence directly. Never print raw control files.
+ process.stdout.write(`🪟 Windows detached stream launch ${launch}: ${diagnostic}\n`);
+ }
// Leave room beyond the 30s PID deadline for the handle's bounded error or
// close event to reach the test, especially on a loaded Windows runner.
}, 45_000);
@@ -356,7 +364,7 @@ describe('spawnDetached', () => {
expect(getOut()).toBe('a b "c"\n');
});
- it.skipIf(IS_POSIX).each([1, 2, 3])('reports a real supervisor bootstrap failure without private paths (launch %i)', async () => {
+ it.skipIf(IS_POSIX).each([1, 2, 3])('reports a real supervisor bootstrap failure without private paths (launch %i)', async (launch) => {
const controlDir = await tmpControlDir();
// Each independent supervisor pays the cold PowerShell/Start-Process cost.
// Use the stream fixture's bounded CI budget so we test the command error,
@@ -365,7 +373,9 @@ describe('spawnDetached', () => {
controlDir, pidTimeoutMs: 30000,
});
await expect(onClose(handle)).rejects.toThrow(/supervisor-stage=failed hresult=-?\d+/);
- expect(await readFile(join(controlDir, 'supervisor-bootstrap.log'), 'utf8')).toMatch(/^failed hresult=-?\d+$/);
+ const diagnostic = await __detachedSpawnTesting.readBootstrapDiagnostic(controlDir, 'supervisor-bootstrap.log');
+ expect(diagnostic).toMatch(/^failed hresult=-?\d+ elapsed-ms=\d+; timeline=reading-job@\d+ms>starting-job@\d+ms>failed@\d+ms$/);
+ process.stdout.write(`🪟 Windows detached expected refusal ${launch}: ${diagnostic}\n`);
}, 45_000);
it.runIf(!IS_POSIX)('cancels a cold supervisor after PID acquisition times out', async () => {