Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 19 additions & 13 deletions scripts/check-affected/command-execution.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ test(
} finally {
child.kill('SIGKILL');
await wait;
killCommandGroup(readRecordedCommandPid(cwd));
fs.rmSync(cwd, { recursive: true, force: true });
}
},
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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 {}
}
83 changes: 75 additions & 8 deletions scripts/check-tmpdir-leaks-model.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -43,13 +48,64 @@ function isProcessAlive(pid: number): boolean {
*/
export function liveRunDirectoryConsumers(): ReadonlySet<string> {
const consumers = new Set<string>();
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 `<pid> <command>` 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<string[]> {
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}/`;
Expand All @@ -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. */
Expand All @@ -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<{
Expand Down
118 changes: 118 additions & 0 deletions scripts/node-test-tmpdir.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
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<false>((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
Expand Down
19 changes: 13 additions & 6 deletions scripts/node-test-tmpdir.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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);
Expand Down Expand Up @@ -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;
Loading
Loading