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..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, @@ -43,13 +48,64 @@ 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 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 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 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. */ +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,15 +114,19 @@ export function runDirectoryNameOf(tmpdir: string): string | undefined { return name.startsWith(TEST_RUN_TMP_PREFIX) ? name : undefined; } -function readAllProcessTmpdirs(): string[] { +type ProcessTmpdir = Readonly<{ pid: number; 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) => + tmpdirsOfEnviron(readEnvironOrEmpty(pid)).map((tmpdir) => ({ pid: Number(pid), tmpdir })), + ); } /** Another user's process, or one that exited mid-scan, contributes nothing. */ @@ -87,13 +147,20 @@ 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=,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 pid = /^\s*(\d+)\s/.exec(line)?.[1]; + if (pid === undefined) return []; + return [...line.matchAll(/\sTMPDIR=(\S+)/g)].map((match) => ({ + pid: Number(pid), + 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..8a01d83489 100644 --- a/scripts/node-test-tmpdir.test.ts +++ b/scripts/node-test-tmpdir.test.ts @@ -86,6 +86,124 @@ 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 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 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(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), + 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]) { + // 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(); + try { + const result = await runCmd( + process.execPath, + ['--experimental-strip-types', WRAPPER, '--experimental-strip-types', '--test', probePath], + { 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')); + await assertOnlyFixtureTreeStopped(result.stderr, pids); + } finally { + 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(); + const wrapper = runCmdBackground( + process.execPath, + ['--experimental-strip-types', WRAPPER, '--experimental-strip-types', '--test', probePath], + { cwd: REPOSITORY_ROOT, env: leftoverProbeEnv(evidenceRoot, true), 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 { + // 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 }); + 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..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 @@ -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); @@ -98,13 +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; -process.exitCode = result.exitCode; +reportStoppedRunDirectoryConsumers(testRunTmpDir, await stopRunDirectoryConsumers(testRunTmpDir)); +process.exitCode = signalExitCode ?? 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..48e4192398 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 @@ -54,10 +56,17 @@ export function setup(): void { } // fallow-ignore-next-line unused-export -export function teardown(): void { - 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 {