From b985f53176d7a04dbd12b19269b8b3e244f25285 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 30 Oct 2026 08:45:37 +0100 Subject: [PATCH 1/3] fix(test): stop processes a test run leaves in its temp directory Vitest global teardown and the node --test wrapper removed the run directory without stopping processes that still held it as TMPDIR, so fixture daemons from killed or timed-out tests ran for weeks. Teardown now SIGKILLs the orphaned Node processes still in the run directory and reports them. Shared tools a test started (adb, emulator) and processes whose parent still runs are left alone. The check-affected execution tests also kill the recorded command group when they fail before learning its pid. Co-Authored-By: Claude Opus 5.5 --- .../check-affected/command-execution.test.ts | 32 ++++--- scripts/check-tmpdir-leaks-model.ts | 94 +++++++++++++++++-- scripts/node-test-tmpdir.test.ts | 39 ++++++++ scripts/node-test-tmpdir.ts | 4 + scripts/vitest-tmpdir-global-setup.test.ts | 48 ++++++++++ scripts/vitest-tmpdir-global-setup.ts | 3 + 6 files changed, 197 insertions(+), 23 deletions(-) diff --git a/scripts/check-affected/command-execution.test.ts b/scripts/check-affected/command-execution.test.ts index 11d4c68513..3c87640cef 100644 --- a/scripts/check-affected/command-execution.test.ts +++ b/scripts/check-affected/command-execution.test.ts @@ -44,6 +44,7 @@ test( } finally { child.kill('SIGKILL'); await wait; + killCommandGroup(readRecordedCommandPid(cwd)); fs.rmSync(cwd, { recursive: true, force: true }); } }, @@ -72,14 +73,8 @@ test( const deadline = Date.now() + 5000; while (!fs.existsSync(ready) && Date.now() < deadline) await setTimeout(20); assert.ok(fs.existsSync(ready)); - commandPid = ( - JSON.parse( - fs.readFileSync( - path.join(cwd, '.cache', 'agent-device', 'validation.lock.active.json'), - 'utf8', - ), - ) as { pid: number } - ).pid; + commandPid = readRecordedCommandPid(cwd); + assert.ok(commandPid, 'the validation parent must record its command group'); parent.child.kill('SIGKILL'); await parent.wait; waiter = runCmdBackground( @@ -109,14 +104,25 @@ test( } finally { parent.child.kill('SIGKILL'); waiter?.child.kill('SIGTERM'); - if (commandPid) { - try { - process.kill(-commandPid, 'SIGKILL'); - } catch {} - } await parent.wait; + killCommandGroup(commandPid ?? readRecordedCommandPid(cwd)); await waiter?.wait; fs.rmSync(cwd, { recursive: true, force: true }); } }, ); + +// The command group runs detached from the validation parent, so a test that fails before it +// learns the group's pid must still find it here; otherwise the group outlives the run. +function readRecordedCommandPid(cwd: string): number | undefined { + const active = path.join(cwd, '.cache', 'agent-device', 'validation.lock.active.json'); + if (!fs.existsSync(active)) return undefined; + return (JSON.parse(fs.readFileSync(active, 'utf8')) as { pid: number | null }).pid ?? undefined; +} + +function killCommandGroup(pid: number | undefined): void { + if (pid === undefined) return; + try { + process.kill(-pid, 'SIGKILL'); + } catch {} +} diff --git a/scripts/check-tmpdir-leaks-model.ts b/scripts/check-tmpdir-leaks-model.ts index 541c6fc1fb..b1ecf4f977 100644 --- a/scripts/check-tmpdir-leaks-model.ts +++ b/scripts/check-tmpdir-leaks-model.ts @@ -43,13 +43,67 @@ function isProcessAlive(pid: number): boolean { */ export function liveRunDirectoryConsumers(): ReadonlySet { const consumers = new Set(); - for (const value of readAllProcessTmpdirs()) { - const name = runDirectoryNameOf(value); + for (const { tmpdir } of readAllProcessTmpdirs()) { + const name = runDirectoryNameOf(tmpdir); if (name !== undefined) consumers.add(name); } return consumers; } +/** + * SIGKILLs the orphaned Node processes that still hold `runDir` as TMPDIR, and returns one + * ` ` line per process. A run's owner calls this after its test processes have + * exited and before it removes the directory. A Node process still inside it whose parent is + * gone is a test fixture whose own cleanup never ran (a killed worker, a timed-out test), and + * nothing else would ever stop it. A shared tool that a test happened to start first (an adb + * server, an emulator, watchman) runs another executable and is left alone, and so is any + * process whose parent still runs and can still clean it up. + */ +export function stopRunDirectoryConsumers(runDir: string): string[] { + const name = runDirectoryNameOf(runDir); + if (name === undefined) return []; + const runtime = path.basename(process.execPath); + const pids = readAllProcessTmpdirs() + .filter( + (entry) => + entry.ppid === 1 && + path.basename(entry.executable) === runtime && + runDirectoryNameOf(entry.tmpdir) === name, + ) + .map((entry) => entry.pid); + if (pids.length === 0) return []; + const commands = describeProcesses(pids); + for (const pid of pids) { + try { + process.kill(pid, 'SIGKILL'); + } catch {} + } + return pids.map((pid) => `${pid} ${commands.get(pid) ?? ''}`.trimEnd()); +} + +function describeProcesses(pids: readonly number[]): ReadonlyMap { + const listing = runCmdSync('ps', ['-o', 'pid=,command=', '-p', pids.join(',')], { + allowFailure: true, + }); + const commands = new Map(); + for (const line of listing.stdout.split('\n')) { + const match = /^\s*(\d+)\s+(.*)$/.exec(line); + if (match) commands.set(Number(match[1]), (match[2] as string).slice(0, 300)); + } + return commands; +} + +/** One stderr block, only when a run's teardown had to stop processes its tests left behind. */ +export function reportStoppedRunDirectoryConsumers( + runDir: string, + stopped: readonly string[], +): void { + if (stopped.length === 0) return; + process.stderr.write( + `[tmpdir] stopped ${stopped.length} process${stopped.length === 1 ? '' : 'es'} still using ${runDir} at teardown:\n${stopped.map((line) => ` ${line}\n`).join('')}`, + ); +} + /** `/tmp/agent-device-test-run-123-abc/nested` → `agent-device-test-run-123-abc`; else undefined. */ export function runDirectoryNameOf(tmpdir: string): string | undefined { const rootPrefix = `${TEST_RUN_TMP_ROOT}/`; @@ -58,21 +112,32 @@ export function runDirectoryNameOf(tmpdir: string): string | undefined { return name.startsWith(TEST_RUN_TMP_PREFIX) ? name : undefined; } -function readAllProcessTmpdirs(): string[] { +/** `executable` is argv[0]. */ +type ProcessTmpdir = Readonly<{ pid: number; ppid: number; executable: string; tmpdir: string }>; + +function readAllProcessTmpdirs(): ProcessTmpdir[] { return process.platform === 'linux' ? readProcTmpdirs() : readPsTmpdirs(); } -function readProcTmpdirs(): string[] { +function readProcTmpdirs(): ProcessTmpdir[] { return fs .readdirSync('/proc') .filter((entry) => /^\d+$/.test(entry)) - .flatMap((pid) => tmpdirsOfEnviron(readEnvironOrEmpty(pid))); + .flatMap((pid) => { + const tmpdirs = tmpdirsOfEnviron(readProcFileOrEmpty(pid, 'environ')); + if (tmpdirs.length === 0) return []; + // `stat` is ` () ...`; comm may itself contain ") ". + const stat = readProcFileOrEmpty(pid, 'stat'); + const ppid = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]); + const executable = readProcFileOrEmpty(pid, 'cmdline').split('\0')[0] ?? ''; + return tmpdirs.map((tmpdir) => ({ pid: Number(pid), ppid, executable, tmpdir })); + }); } /** Another user's process, or one that exited mid-scan, contributes nothing. */ -function readEnvironOrEmpty(pid: string): string { +function readProcFileOrEmpty(pid: string, file: 'environ' | 'stat' | 'cmdline'): string { try { - return fs.readFileSync(`/proc/${pid}/environ`, 'latin1'); + return fs.readFileSync(`/proc/${pid}/${file}`, 'latin1'); } catch { return ''; } @@ -87,13 +152,22 @@ function tmpdirsOfEnviron(environ: string): string[] { // macOS (and other BSDs): -E appends the environment to each command line. Every process's // environment is a few MB on a busy host — well past spawnSync's 1 MB default. -function readPsTmpdirs(): string[] { - const listing = runCmdSync('ps', ['-axEww', '-o', 'command='], { +function readPsTmpdirs(): ProcessTmpdir[] { + const listing = runCmdSync('ps', ['-axEww', '-o', 'pid=,ppid=,command='], { allowFailure: true, maxBuffer: 64 * 1024 * 1024, }); if (listing.exitCode !== 0) return []; - return [...listing.stdout.matchAll(/(?:^|\s)TMPDIR=(\S+)/g)].map((match) => match[1] as string); + return listing.stdout.split('\n').flatMap((line) => { + const head = /^\s*(\d+)\s+(\d+)\s+(\S+)/.exec(line); + if (!head) return []; + return [...line.matchAll(/\sTMPDIR=(\S+)/g)].map((match) => ({ + pid: Number(head[1]), + ppid: Number(head[2]), + executable: head[3] as string, + tmpdir: match[1] as string, + })); + }); } export type RunDirectoryLiveness = Readonly<{ diff --git a/scripts/node-test-tmpdir.test.ts b/scripts/node-test-tmpdir.test.ts index 72afb2d967..cd0045aa7a 100644 --- a/scripts/node-test-tmpdir.test.ts +++ b/scripts/node-test-tmpdir.test.ts @@ -86,6 +86,45 @@ test('the wrapper redirects a node --test child TMPDIR and removes it after the } }); +test('the wrapper stops an orphaned Node fixture still using the run directory, not a shared tool', async () => { + const evidenceRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'node-test-tmpdir-reap-')); + const evidencePath = path.join(evidenceRoot, 'pids.json'); + const probeName = `node-test-tmpdir-probe-reap-${process.pid}-${crypto.randomUUID()}.test.ts`; + const probePath = path.join(REPOSITORY_ROOT, 'scripts', probeName); + fs.writeFileSync( + probePath, + `import fs from 'node:fs'; +import { test } from 'node:test'; +import { runCmdDetached } from '@agent-device/host-kit/command'; + +test('probe leaves a Node fixture and a non-Node tool running past its own exit', () => { + const fixture = runCmdDetached(process.execPath, ['-e', 'setInterval(() => {}, 1000)']); + const tool = runCmdDetached('/bin/sleep', ['60']); + fs.writeFileSync(${JSON.stringify(evidencePath)}, JSON.stringify({ fixture, tool })); +}); +`, + ); + let pids: { fixture: number; tool: number } | undefined; + try { + const result = await runCmd( + process.execPath, + ['--experimental-strip-types', WRAPPER, '--experimental-strip-types', '--test', probePath], + { cwd: REPOSITORY_ROOT, timeoutMs: 30_000 }, + ); + assert.equal(result.exitCode, 0, `probe run failed:\n${result.stdout}\n${result.stderr}`); + pids = JSON.parse(fs.readFileSync(evidencePath, 'utf8')); + await waitFor(() => !isAlive(pids!.fixture), 5_000, 'the leaked fixture outlived its run'); + assert.match(result.stderr, new RegExp(`\\[tmpdir\\] stopped [^]*\\n ${pids!.fixture} `)); + assert.equal(isAlive(pids!.tool), true, 'a non-Node process is not the run’s to stop'); + } finally { + for (const pid of pids ? [pids.fixture, pids.tool] : []) { + if (isAlive(pid)) process.kill(pid, 'SIGKILL'); + } + fs.rmSync(probePath, { force: true }); + fs.rmSync(evidenceRoot, { recursive: true, force: true }); + } +}); + test('the wrapper still cleans up and forwards a nonzero exit code when the child fails', async () => { // Diffing the whole shared TEST_RUN_TMP_ROOT listing is racy here: this // file itself runs as one of several node --test files/workers sharing diff --git a/scripts/node-test-tmpdir.ts b/scripts/node-test-tmpdir.ts index 35cfb89dac..1f4fcc5fce 100644 --- a/scripts/node-test-tmpdir.ts +++ b/scripts/node-test-tmpdir.ts @@ -33,6 +33,8 @@ import { TEST_RUN_TMP_ROOT, pruneAbandonedRunDirectories, reportPrunedRunDirectories, + reportStoppedRunDirectoryConsumers, + stopRunDirectoryConsumers, } from './check-tmpdir-leaks-model.ts'; const forwardedArgs = process.argv.slice(2); @@ -107,4 +109,6 @@ for (const signal of ['SIGINT', 'SIGTERM'] as const) { } const result = await wait; +// Only after the child exits: on a forwarded signal its own cleanup may still be running. +reportStoppedRunDirectoryConsumers(testRunTmpDir, stopRunDirectoryConsumers(testRunTmpDir)); process.exitCode = result.exitCode; diff --git a/scripts/vitest-tmpdir-global-setup.test.ts b/scripts/vitest-tmpdir-global-setup.test.ts index 0154ae7328..2c4675a602 100644 --- a/scripts/vitest-tmpdir-global-setup.test.ts +++ b/scripts/vitest-tmpdir-global-setup.test.ts @@ -4,6 +4,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { test } from 'node:test'; +import { setTimeout } from 'node:timers/promises'; import { fileURLToPath } from 'node:url'; import { runCmd } from '@agent-device/host-kit/command'; import { TEST_RUN_TMP_PREFIX, TEST_RUN_TMP_ROOT } from './check-tmpdir-leaks-model.ts'; @@ -113,3 +114,50 @@ test('noop probe: the run itself is the subject', () => {}); fs.rmSync(probePath, { force: true }); } }); + +test('global teardown stops a detached child a test left running in the run directory', async () => { + const stamp = crypto.randomUUID(); + const probeName = `vitest-tmpdir-reap-probe-${process.pid}-${stamp}.test.ts`; + const probePath = path.join(REPOSITORY_ROOT, 'src', '__tests__', probeName); + const evidenceRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'vitest-tmpdir-reap-test-')); + const evidencePath = path.join(evidenceRoot, 'child-pid.txt'); + fs.writeFileSync( + probePath, + `import fs from 'node:fs'; +import { test } from 'vitest'; +import { runCmdDetached } from '@agent-device/host-kit/command'; + +test('probe leaves a detached child running past its own worker', () => { + const childPid = runCmdDetached(process.execPath, ['-e', 'setInterval(() => {}, 1000)']); + fs.writeFileSync(${JSON.stringify(evidencePath)}, String(childPid)); +}); +`, + ); + let childPid: number | undefined; + try { + const result = await runCmd( + path.join(REPOSITORY_ROOT, 'node_modules', '.bin', 'vitest'), + ['run', '--project', 'unit-core', probePath], + { cwd: REPOSITORY_ROOT, timeoutMs: 30_000 }, + ); + assert.equal(result.exitCode, 0, `probe run failed:\n${result.stdout}\n${result.stderr}`); + childPid = Number(fs.readFileSync(evidencePath, 'utf8')); + const deadline = Date.now() + 5_000; + while (isAlive(childPid) && Date.now() < deadline) await setTimeout(100); + assert.equal(isAlive(childPid), false, 'the leaked child outlived its run'); + assert.match(result.stderr, new RegExp(`\\[tmpdir\\] stopped [^]*\\n ${childPid} `)); + } finally { + if (childPid && isAlive(childPid)) process.kill(childPid, 'SIGKILL'); + fs.rmSync(probePath, { force: true }); + fs.rmSync(evidenceRoot, { recursive: true, force: true }); + } +}); + +function isAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } +} diff --git a/scripts/vitest-tmpdir-global-setup.ts b/scripts/vitest-tmpdir-global-setup.ts index 4814106f99..f4ff2b3087 100644 --- a/scripts/vitest-tmpdir-global-setup.ts +++ b/scripts/vitest-tmpdir-global-setup.ts @@ -6,6 +6,8 @@ import { TEST_RUN_TMP_ROOT, pruneAbandonedRunDirectories, reportPrunedRunDirectories, + reportStoppedRunDirectoryConsumers, + stopRunDirectoryConsumers, } from './check-tmpdir-leaks-model.ts'; // os.tmpdir() reads TMPDIR on every call, so redirecting it here covers every @@ -55,6 +57,7 @@ export function setup(): void { // fallow-ignore-next-line unused-export export function teardown(): void { + reportStoppedRunDirectoryConsumers(testRunTmpDir, stopRunDirectoryConsumers(testRunTmpDir)); fs.rmSync(testRunTmpDir, { recursive: true, force: true }); restoreEnv('TMPDIR', previousTmpDir); restoreEnv('AGENT_DEVICE_SWIFT_CACHE_DIR', previousSwiftCacheDir); From 8a3d724c932b3cc94b4d38d2d73fd99feba1dd61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 30 Oct 2026 10:19:26 +0100 Subject: [PATCH 2/3] fix(test): stop leftover process trees after a run's own processes Address review: a root is now a Node process in the run directory whose parent is neither the run owner nor another run process, so subreapers and a PID 1 runner are handled, and each root's descendants are stopped too. Reuse the host-kit process table and signal helpers. The vitest teardown always removes the directory and restores env, and the node --test wrapper waits for its child after a forwarded signal, then stops leftovers; a second signal still exits at once. Co-Authored-By: Claude Opus 5.5 --- scripts/check-tmpdir-leaks-model.ts | 103 ++++++++++++-------------- scripts/node-test-tmpdir.test.ts | 83 +++++++++++++++++---- scripts/node-test-tmpdir.ts | 19 +++-- scripts/vitest-tmpdir-global-setup.ts | 16 ++-- 4 files changed, 139 insertions(+), 82 deletions(-) diff --git a/scripts/check-tmpdir-leaks-model.ts b/scripts/check-tmpdir-leaks-model.ts index b1ecf4f977..580a7c4f5d 100644 --- a/scripts/check-tmpdir-leaks-model.ts +++ b/scripts/check-tmpdir-leaks-model.ts @@ -1,6 +1,11 @@ import fs from 'node:fs'; import path from 'node:path'; import { runCmdSync } from '@agent-device/host-kit/command'; +import { + expandProcessTree, + listHostProcesses, + signalPidsBestEffort, +} from '@agent-device/host-kit/process'; // Every test run (Vitest via scripts/vitest-tmpdir-global-setup.ts, node --test // via scripts/node-test-tmpdir.ts) redirects TMPDIR into one disposable, @@ -51,46 +56,43 @@ export function liveRunDirectoryConsumers(): ReadonlySet { } /** - * SIGKILLs the orphaned Node processes that still hold `runDir` as TMPDIR, and returns one - * ` ` line per process. A run's owner calls this after its test processes have - * exited and before it removes the directory. A Node process still inside it whose parent is - * gone is a test fixture whose own cleanup never ran (a killed worker, a timed-out test), and - * nothing else would ever stop it. A shared tool that a test happened to start first (an adb - * server, an emulator, watchman) runs another executable and is left alone, and so is any - * process whose parent still runs and can still clean it up. + * SIGKILLs the process trees that tests left in `runDir` and returns one ` ` line + * per stopped process. A run's owner calls this after its test processes have exited and before + * it removes the directory. A root is a Node process that holds `runDir` as TMPDIR and whose + * parent is neither the owner nor another process of this run: a test fixture whose own cleanup + * never ran (a killed worker, a timed-out test), reparented to init or a subreaper. Nothing + * else would ever stop it. A shared tool that a test happened to start first (an adb server, an + * emulator, watchman) runs another executable and is left alone, and so is any process whose + * parent in this run still runs and can still clean it up. */ -export function stopRunDirectoryConsumers(runDir: string): string[] { +export async function stopRunDirectoryConsumers(runDir: string): Promise { const name = runDirectoryNameOf(runDir); if (name === undefined) return []; + const consumers = new Set( + readAllProcessTmpdirs() + .filter((entry) => entry.pid !== process.pid && runDirectoryNameOf(entry.tmpdir) === name) + .map((entry) => entry.pid), + ); + if (consumers.size === 0) return []; const runtime = path.basename(process.execPath); - const pids = readAllProcessTmpdirs() - .filter( - (entry) => - entry.ppid === 1 && - path.basename(entry.executable) === runtime && - runDirectoryNameOf(entry.tmpdir) === name, - ) - .map((entry) => entry.pid); - if (pids.length === 0) return []; - const commands = describeProcesses(pids); - for (const pid of pids) { - try { - process.kill(pid, 'SIGKILL'); - } catch {} - } - return pids.map((pid) => `${pid} ${commands.get(pid) ?? ''}`.trimEnd()); -} - -function describeProcesses(pids: readonly number[]): ReadonlyMap { - const listing = runCmdSync('ps', ['-o', 'pid=,command=', '-p', pids.join(',')], { - allowFailure: true, - }); - const commands = new Map(); - for (const line of listing.stdout.split('\n')) { - const match = /^\s*(\d+)\s+(.*)$/.exec(line); - if (match) commands.set(Number(match[1]), (match[2] as string).slice(0, 300)); - } - return commands; + const processes = await listHostProcesses({ timeoutMs: 10_000 }); + const roots = processes.filter( + (entry) => + consumers.has(entry.pid) && + entry.ppid !== undefined && + entry.ppid !== process.pid && + !consumers.has(entry.ppid) && + path.basename(entry.command.split(' ')[0] ?? '') === runtime, + ); + const stopped = expandProcessTree( + roots.map((entry) => entry.pid), + processes, + ); + signalPidsBestEffort( + stopped.map((entry) => entry.pid), + 'SIGKILL', + ); + return stopped.map((entry) => `${entry.pid} ${entry.command.slice(0, 300)}`.trimEnd()); } /** One stderr block, only when a run's teardown had to stop processes its tests left behind. */ @@ -112,8 +114,7 @@ export function runDirectoryNameOf(tmpdir: string): string | undefined { return name.startsWith(TEST_RUN_TMP_PREFIX) ? name : undefined; } -/** `executable` is argv[0]. */ -type ProcessTmpdir = Readonly<{ pid: number; ppid: number; executable: string; tmpdir: string }>; +type ProcessTmpdir = Readonly<{ pid: number; tmpdir: string }>; function readAllProcessTmpdirs(): ProcessTmpdir[] { return process.platform === 'linux' ? readProcTmpdirs() : readPsTmpdirs(); @@ -123,21 +124,15 @@ function readProcTmpdirs(): ProcessTmpdir[] { return fs .readdirSync('/proc') .filter((entry) => /^\d+$/.test(entry)) - .flatMap((pid) => { - const tmpdirs = tmpdirsOfEnviron(readProcFileOrEmpty(pid, 'environ')); - if (tmpdirs.length === 0) return []; - // `stat` is ` () ...`; comm may itself contain ") ". - const stat = readProcFileOrEmpty(pid, 'stat'); - const ppid = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]); - const executable = readProcFileOrEmpty(pid, 'cmdline').split('\0')[0] ?? ''; - return tmpdirs.map((tmpdir) => ({ pid: Number(pid), ppid, executable, tmpdir })); - }); + .flatMap((pid) => + tmpdirsOfEnviron(readEnvironOrEmpty(pid)).map((tmpdir) => ({ pid: Number(pid), tmpdir })), + ); } /** Another user's process, or one that exited mid-scan, contributes nothing. */ -function readProcFileOrEmpty(pid: string, file: 'environ' | 'stat' | 'cmdline'): string { +function readEnvironOrEmpty(pid: string): string { try { - return fs.readFileSync(`/proc/${pid}/${file}`, 'latin1'); + return fs.readFileSync(`/proc/${pid}/environ`, 'latin1'); } catch { return ''; } @@ -153,18 +148,16 @@ function tmpdirsOfEnviron(environ: string): string[] { // macOS (and other BSDs): -E appends the environment to each command line. Every process's // environment is a few MB on a busy host — well past spawnSync's 1 MB default. function readPsTmpdirs(): ProcessTmpdir[] { - const listing = runCmdSync('ps', ['-axEww', '-o', 'pid=,ppid=,command='], { + const listing = runCmdSync('ps', ['-axEww', '-o', 'pid=,command='], { allowFailure: true, maxBuffer: 64 * 1024 * 1024, }); if (listing.exitCode !== 0) return []; return listing.stdout.split('\n').flatMap((line) => { - const head = /^\s*(\d+)\s+(\d+)\s+(\S+)/.exec(line); - if (!head) return []; + const pid = /^\s*(\d+)\s/.exec(line)?.[1]; + if (pid === undefined) return []; return [...line.matchAll(/\sTMPDIR=(\S+)/g)].map((match) => ({ - pid: Number(head[1]), - ppid: Number(head[2]), - executable: head[3] as string, + pid: Number(pid), tmpdir: match[1] as string, })); }); diff --git a/scripts/node-test-tmpdir.test.ts b/scripts/node-test-tmpdir.test.ts index cd0045aa7a..4fff34fdd8 100644 --- a/scripts/node-test-tmpdir.test.ts +++ b/scripts/node-test-tmpdir.test.ts @@ -86,25 +86,57 @@ test('the wrapper redirects a node --test child TMPDIR and removes it after the } }); -test('the wrapper stops an orphaned Node fixture still using the run directory, not a shared tool', async () => { - const evidenceRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'node-test-tmpdir-reap-')); - const evidencePath = path.join(evidenceRoot, 'pids.json'); +type LeftoverPids = { fixture: number; fixtureChild: number; tool: number }; + +// The probe leaves a Node fixture (with a child of its own) and a non-Node tool running, both +// detached so they outlive the probe. With `hold`, it then waits until the run is interrupted. +function writeLeftoverProbe(evidenceRoot: string, hold: boolean): string { const probeName = `node-test-tmpdir-probe-reap-${process.pid}-${crypto.randomUUID()}.test.ts`; const probePath = path.join(REPOSITORY_ROOT, 'scripts', probeName); + const childPidPath = path.join(evidenceRoot, 'fixture-child.txt'); + const fixtureSource = `const child = require('node:child_process').spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' }); require('node:fs').writeFileSync(${JSON.stringify(childPidPath)}, String(child.pid)); setInterval(() => {}, 1000);`; fs.writeFileSync( probePath, `import fs from 'node:fs'; import { test } from 'node:test'; import { runCmdDetached } from '@agent-device/host-kit/command'; -test('probe leaves a Node fixture and a non-Node tool running past its own exit', () => { - const fixture = runCmdDetached(process.execPath, ['-e', 'setInterval(() => {}, 1000)']); +test('probe leaves a Node fixture and a non-Node tool running past its own exit', async () => { + const fixture = runCmdDetached(process.execPath, ['-e', ${JSON.stringify(fixtureSource)}]); const tool = runCmdDetached('/bin/sleep', ['60']); - fs.writeFileSync(${JSON.stringify(evidencePath)}, JSON.stringify({ fixture, tool })); + while (!fs.existsSync(${JSON.stringify(childPidPath)})) await new Promise((resolve) => setTimeout(resolve, 20)); + const fixtureChild = Number(fs.readFileSync(${JSON.stringify(childPidPath)}, 'utf8')); + fs.writeFileSync(${JSON.stringify(path.join(evidenceRoot, 'pids.json'))}, JSON.stringify({ fixture, fixtureChild, tool })); + ${hold ? 'await new Promise((resolve) => setTimeout(resolve, 60_000));' : ''} }); `, ); - let pids: { fixture: number; tool: number } | undefined; + return probePath; +} + +async function assertOnlyFixtureTreeStopped(stderr: string, pids: LeftoverPids): Promise { + await waitFor( + () => !isAlive(pids.fixture) && !isAlive(pids.fixtureChild), + 5_000, + 'the leaked fixture or its child outlived its run', + ); + assert.match(stderr, new RegExp(`\\[tmpdir\\] stopped [^]*\\n ${pids.fixture} `)); + assert.match(stderr, new RegExp(`\\[tmpdir\\] stopped [^]*\\n ${pids.fixtureChild} `)); + assert.equal(isAlive(pids.tool), true, 'a non-Node process is not the run’s to stop'); +} + +function killLeftovers(evidenceRoot: string): void { + const evidencePath = path.join(evidenceRoot, 'pids.json'); + if (!fs.existsSync(evidencePath)) return; + const pids = JSON.parse(fs.readFileSync(evidencePath, 'utf8')) as LeftoverPids; + for (const pid of [pids.fixture, pids.fixtureChild, pids.tool]) { + if (isAlive(pid)) process.kill(pid, 'SIGKILL'); + } +} + +test('the wrapper stops an orphaned Node fixture tree still using the run directory, not a shared tool', async () => { + const evidenceRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'node-test-tmpdir-reap-')); + const probePath = writeLeftoverProbe(evidenceRoot, false); try { const result = await runCmd( process.execPath, @@ -112,14 +144,37 @@ test('probe leaves a Node fixture and a non-Node tool running past its own exit' { cwd: REPOSITORY_ROOT, timeoutMs: 30_000 }, ); assert.equal(result.exitCode, 0, `probe run failed:\n${result.stdout}\n${result.stderr}`); - pids = JSON.parse(fs.readFileSync(evidencePath, 'utf8')); - await waitFor(() => !isAlive(pids!.fixture), 5_000, 'the leaked fixture outlived its run'); - assert.match(result.stderr, new RegExp(`\\[tmpdir\\] stopped [^]*\\n ${pids!.fixture} `)); - assert.equal(isAlive(pids!.tool), true, 'a non-Node process is not the run’s to stop'); + const pids = JSON.parse(fs.readFileSync(path.join(evidenceRoot, 'pids.json'), 'utf8')); + await assertOnlyFixtureTreeStopped(result.stderr, pids); } finally { - for (const pid of pids ? [pids.fixture, pids.tool] : []) { - if (isAlive(pid)) process.kill(pid, 'SIGKILL'); - } + killLeftovers(evidenceRoot); + fs.rmSync(probePath, { force: true }); + fs.rmSync(evidenceRoot, { recursive: true, force: true }); + } +}); + +test('an interrupted wrapper waits for its child, then stops the leftovers and exits 130', async () => { + const evidenceRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'node-test-tmpdir-reap-signal-')); + const probePath = writeLeftoverProbe(evidenceRoot, true); + const wrapper = runCmdBackground( + process.execPath, + ['--experimental-strip-types', WRAPPER, '--experimental-strip-types', '--test', probePath], + { cwd: REPOSITORY_ROOT, allowFailure: true }, + ); + try { + const evidencePath = path.join(evidenceRoot, 'pids.json'); + await waitFor(() => fs.existsSync(evidencePath), 20_000, 'probe never reported its pids'); + wrapper.child.kill('SIGINT'); + const result = await wrapper.wait; + assert.equal(result.exitCode, 130, result.stderr); + await assertOnlyFixtureTreeStopped( + result.stderr, + JSON.parse(fs.readFileSync(evidencePath, 'utf8')), + ); + } finally { + wrapper.child.kill('SIGKILL'); + await wrapper.wait; + killLeftovers(evidenceRoot); fs.rmSync(probePath, { force: true }); fs.rmSync(evidenceRoot, { recursive: true, force: true }); } diff --git a/scripts/node-test-tmpdir.ts b/scripts/node-test-tmpdir.ts index 1f4fcc5fce..b5f7afe847 100644 --- a/scripts/node-test-tmpdir.ts +++ b/scripts/node-test-tmpdir.ts @@ -16,9 +16,9 @@ // alike — without touching any of them, exactly like the Vitest lane. // // Cleanup runs from the process 'exit' event rather than only a try/finally, -// so it fires for normal completion, a thrown error, AND a signal this -// process forwards to a still-running child (Ctrl-C locally, or a CI job -// cancellation): the signal handlers below call `process.exit()`, which +// so it fires for normal completion, a thrown error, AND a signal (Ctrl-C +// locally, or a CI job cancellation): the first signal is forwarded and the +// run ends when the child exits; a second one calls `process.exit()`, which // triggers 'exit' synchronously before the process actually terminates. // Only a SIGKILL against this wrapper itself bypasses all of that; the next // run on the host prunes what such a kill left behind (see @@ -100,15 +100,18 @@ const { child, wait } = runCmdBackground(process.execPath, forwardedArgs, { allowFailure: true, }); +// A forwarded signal waits for the child: its own cleanup may still be running, and leftovers +// are stopped only after it exits. A second signal stops waiting. +let signalExitCode: number | undefined; for (const signal of ['SIGINT', 'SIGTERM'] as const) { process.on(signal, () => { - child.kill(signal); + if (signalExitCode !== undefined) process.exit(signalExitCode); // 128 + signal number is the shell convention for a signal-terminated exit. - process.exit(signal === 'SIGINT' ? 130 : 143); + signalExitCode = signal === 'SIGINT' ? 130 : 143; + child.kill(signal); }); } const result = await wait; -// Only after the child exits: on a forwarded signal its own cleanup may still be running. -reportStoppedRunDirectoryConsumers(testRunTmpDir, stopRunDirectoryConsumers(testRunTmpDir)); -process.exitCode = result.exitCode; +reportStoppedRunDirectoryConsumers(testRunTmpDir, await stopRunDirectoryConsumers(testRunTmpDir)); +process.exitCode = signalExitCode ?? result.exitCode; diff --git a/scripts/vitest-tmpdir-global-setup.ts b/scripts/vitest-tmpdir-global-setup.ts index f4ff2b3087..48e4192398 100644 --- a/scripts/vitest-tmpdir-global-setup.ts +++ b/scripts/vitest-tmpdir-global-setup.ts @@ -56,11 +56,17 @@ export function setup(): void { } // fallow-ignore-next-line unused-export -export function teardown(): void { - reportStoppedRunDirectoryConsumers(testRunTmpDir, stopRunDirectoryConsumers(testRunTmpDir)); - fs.rmSync(testRunTmpDir, { recursive: true, force: true }); - restoreEnv('TMPDIR', previousTmpDir); - restoreEnv('AGENT_DEVICE_SWIFT_CACHE_DIR', previousSwiftCacheDir); +export async function teardown(): Promise { + try { + reportStoppedRunDirectoryConsumers( + testRunTmpDir, + await stopRunDirectoryConsumers(testRunTmpDir), + ); + } finally { + fs.rmSync(testRunTmpDir, { recursive: true, force: true }); + restoreEnv('TMPDIR', previousTmpDir); + restoreEnv('AGENT_DEVICE_SWIFT_CACHE_DIR', previousSwiftCacheDir); + } } function restoreEnv(key: string, value: string | undefined): void { From 598c4b1322eac97d72a2a9f2b86cb45d70edfcd0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 30 Oct 2026 10:53:54 +0100 Subject: [PATCH 3/3] test(tooling): harden leftover-process wrapper tests Pass probe paths through env and argv instead of building them into source, publish pid files by rename so a reader never sees pid 0, and interrupt a still-running wrapper before SIGKILL in cleanup. Co-Authored-By: Claude Opus 5.5 --- scripts/node-test-tmpdir.test.ts | 68 +++++++++++++++++++++----------- 1 file changed, 46 insertions(+), 22 deletions(-) diff --git a/scripts/node-test-tmpdir.test.ts b/scripts/node-test-tmpdir.test.ts index 4fff34fdd8..8a01d83489 100644 --- a/scripts/node-test-tmpdir.test.ts +++ b/scripts/node-test-tmpdir.test.ts @@ -88,32 +88,46 @@ test('the wrapper redirects a node --test child TMPDIR and removes it after the type LeftoverPids = { fixture: number; fixtureChild: number; tool: number }; +// Started with its child-pid path as argv[1]. Both files are published by rename, so a reader +// never sees a partial pid. +const LEFTOVER_FIXTURE_SOURCE = `const fs = require('node:fs'); +const child = require('node:child_process').spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' }); +fs.writeFileSync(process.argv[1] + '.tmp', String(child.pid)); +fs.renameSync(process.argv[1] + '.tmp', process.argv[1]); +setInterval(() => {}, 1000);`; + // The probe leaves a Node fixture (with a child of its own) and a non-Node tool running, both -// detached so they outlive the probe. With `hold`, it then waits until the run is interrupted. -function writeLeftoverProbe(evidenceRoot: string, hold: boolean): string { - const probeName = `node-test-tmpdir-probe-reap-${process.pid}-${crypto.randomUUID()}.test.ts`; - const probePath = path.join(REPOSITORY_ROOT, 'scripts', probeName); - const childPidPath = path.join(evidenceRoot, 'fixture-child.txt'); - const fixtureSource = `const child = require('node:child_process').spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' }); require('node:fs').writeFileSync(${JSON.stringify(childPidPath)}, String(child.pid)); setInterval(() => {}, 1000);`; - fs.writeFileSync( - probePath, - `import fs from 'node:fs'; +// detached so they outlive the probe. With REAP_HOLD set, it then waits to be interrupted. +const LEFTOVER_PROBE_SOURCE = `import fs from 'node:fs'; +import path from 'node:path'; import { test } from 'node:test'; import { runCmdDetached } from '@agent-device/host-kit/command'; test('probe leaves a Node fixture and a non-Node tool running past its own exit', async () => { - const fixture = runCmdDetached(process.execPath, ['-e', ${JSON.stringify(fixtureSource)}]); + const root = process.env.REAP_EVIDENCE_ROOT; + const childPidPath = path.join(root, 'fixture-child.txt'); + const fixture = runCmdDetached(process.execPath, ['-e', ${JSON.stringify(LEFTOVER_FIXTURE_SOURCE)}, childPidPath]); const tool = runCmdDetached('/bin/sleep', ['60']); - while (!fs.existsSync(${JSON.stringify(childPidPath)})) await new Promise((resolve) => setTimeout(resolve, 20)); - const fixtureChild = Number(fs.readFileSync(${JSON.stringify(childPidPath)}, 'utf8')); - fs.writeFileSync(${JSON.stringify(path.join(evidenceRoot, 'pids.json'))}, JSON.stringify({ fixture, fixtureChild, tool })); - ${hold ? 'await new Promise((resolve) => setTimeout(resolve, 60_000));' : ''} + while (!fs.existsSync(childPidPath)) await new Promise((resolve) => setTimeout(resolve, 20)); + const fixtureChild = Number(fs.readFileSync(childPidPath, 'utf8')); + const pidsPath = path.join(root, 'pids.json'); + fs.writeFileSync(pidsPath + '.tmp', JSON.stringify({ fixture, fixtureChild, tool })); + fs.renameSync(pidsPath + '.tmp', pidsPath); + if (process.env.REAP_HOLD) await new Promise((resolve) => setTimeout(resolve, 60_000)); }); -`, - ); +`; + +function writeLeftoverProbe(): string { + const probeName = `node-test-tmpdir-probe-reap-${process.pid}-${crypto.randomUUID()}.test.ts`; + const probePath = path.join(REPOSITORY_ROOT, 'scripts', probeName); + fs.writeFileSync(probePath, LEFTOVER_PROBE_SOURCE); return probePath; } +function leftoverProbeEnv(evidenceRoot: string, hold: boolean): NodeJS.ProcessEnv { + return { ...process.env, REAP_EVIDENCE_ROOT: evidenceRoot, REAP_HOLD: hold ? '1' : '' }; +} + async function assertOnlyFixtureTreeStopped(stderr: string, pids: LeftoverPids): Promise { await waitFor( () => !isAlive(pids.fixture) && !isAlive(pids.fixtureChild), @@ -130,18 +144,19 @@ function killLeftovers(evidenceRoot: string): void { if (!fs.existsSync(evidencePath)) return; const pids = JSON.parse(fs.readFileSync(evidencePath, 'utf8')) as LeftoverPids; for (const pid of [pids.fixture, pids.fixtureChild, pids.tool]) { - if (isAlive(pid)) process.kill(pid, 'SIGKILL'); + // pid 0 or a negative pid would address a whole process group. + if (Number.isInteger(pid) && pid > 0 && isAlive(pid)) process.kill(pid, 'SIGKILL'); } } test('the wrapper stops an orphaned Node fixture tree still using the run directory, not a shared tool', async () => { const evidenceRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'node-test-tmpdir-reap-')); - const probePath = writeLeftoverProbe(evidenceRoot, false); + const probePath = writeLeftoverProbe(); try { const result = await runCmd( process.execPath, ['--experimental-strip-types', WRAPPER, '--experimental-strip-types', '--test', probePath], - { cwd: REPOSITORY_ROOT, timeoutMs: 30_000 }, + { cwd: REPOSITORY_ROOT, env: leftoverProbeEnv(evidenceRoot, false), timeoutMs: 30_000 }, ); assert.equal(result.exitCode, 0, `probe run failed:\n${result.stdout}\n${result.stderr}`); const pids = JSON.parse(fs.readFileSync(path.join(evidenceRoot, 'pids.json'), 'utf8')); @@ -155,11 +170,11 @@ test('the wrapper stops an orphaned Node fixture tree still using the run direct test('an interrupted wrapper waits for its child, then stops the leftovers and exits 130', async () => { const evidenceRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'node-test-tmpdir-reap-signal-')); - const probePath = writeLeftoverProbe(evidenceRoot, true); + const probePath = writeLeftoverProbe(); const wrapper = runCmdBackground( process.execPath, ['--experimental-strip-types', WRAPPER, '--experimental-strip-types', '--test', probePath], - { cwd: REPOSITORY_ROOT, allowFailure: true }, + { cwd: REPOSITORY_ROOT, env: leftoverProbeEnv(evidenceRoot, true), allowFailure: true }, ); try { const evidencePath = path.join(evidenceRoot, 'pids.json'); @@ -172,7 +187,16 @@ test('an interrupted wrapper waits for its child, then stops the leftovers and e JSON.parse(fs.readFileSync(evidencePath, 'utf8')), ); } finally { - wrapper.child.kill('SIGKILL'); + // An early failure leaves the wrapper running: interrupt it so it stops its own child and + // removes the run directory, and SIGKILL it only if that does not finish in time. + if (wrapper.child.exitCode === null && wrapper.child.signalCode === null) { + wrapper.child.kill('SIGINT'); + const settled = await Promise.race([ + wrapper.wait.then(() => true), + new Promise((resolve) => setTimeout(() => resolve(false), 10_000)), + ]); + if (!settled) wrapper.child.kill('SIGKILL'); + } await wrapper.wait; killLeftovers(evidenceRoot); fs.rmSync(probePath, { force: true });