Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

The CLI command test ends everything it starts, and fails when a run leaves a process behind. (#854)

Dee8e191956cbd6
diff --git a/cli/src/cliCommand.spec.ts b/cli/src/cliCommand.spec.ts
index 053b0b9ac..1105f8c9a 100644
--- a/cli/src/cliCommand.spec.ts
+++ b/cli/src/cliCommand.spec.ts
@@ -7,6 +7,7 @@ import { fileURLToPath } from 'url'
import { afterEach, describe, expect, it } from 'vitest'
import { listenLocalSocket, localSocketPath } from './lib/localSocket.js'
import { fakePlatform } from './testing/fakePlatform.js'
+import { alive, SpawnedRuns } from './testing/spawnedRuns.js'
const CLI_ROOT = fileURLToPath(new URL('..', import.meta.url))
const CLI_SOURCE = join(CLI_ROOT, 'src', 'cli.ts')
@@ -14,8 +15,19 @@ const TSX = join(CLI_ROOT, 'node_modules', 'tsx', 'dist', 'cli.mjs')
const dirs: string[] = []
const children: ChildProcess[] = []
const servers: Server[] = []
+/**
+ * Every CLI run, each in a process group of its own, ended with everything it started at teardown and
+ * at its deadline (testing/spawnedRuns.ts). Twelve `cli.ts start` runs of this file that never exited
+ * were found nine hours later, one spinning a core: tsx runs the CLI in a child of its own, a dev-mode
+ * start becomes the daemon, and nothing killed either when a test timed out. The daemon a run's pid
+ * file names counts as the run's when it is this checkout's CLI.
+ */
+const runs = new SpawnedRuns((command) => command.includes(CLI_SOURCE))
+// A worker that exits with a run still going (a cancelled run) takes the run's group with it.
+process.once('exit', () => runs.killAllSync())
afterEach(async () => {
+ const { leftBehind, survivors } = await runs.endAll()
for (const child of children.splice(0)) {
if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL')
}
@@ -24,6 +36,10 @@ afterEach(async () => {
await new Promise<void>((resolve) => server.close(() => resolve()))
}
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
+ // The guard: a run that left a process behind fails the test that ran it, even though teardown has
+ // ended it by now. Otherwise the next leak is found the way the last one was, hours later.
+ if (survivors.length) throw new Error(`processes this test started would not die:\n${survivors.join('\n')}`)
+ if (leftBehind.length) throw new Error(`a CLI run left processes behind:\n${leftBehind.join('\n')}`)
})
/** A throwaway HOME for one CLI run; every path the CLI writes is under it. */
@@ -59,21 +75,19 @@ function envFor(root: string, extra: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv
}
}
-function run(...args: string[]) {
- return spawnSync(process.execPath, [TSX, CLI_SOURCE, ...args], { cwd: CLI_ROOT, encoding: 'utf8', env: envFor(freshRoot()) })
+/** `harness [args]` under a throwaway HOME, to the end. Never blocking this process: a test that also
+ * SERVES the CLI something (a manifest on the loopback) has to keep its own event loop free while the
+ * child asks for it. One that has not ended within 15s is ended, everything it started with it, and
+ * comes back with `timedOut`. */
+async function runAsync(root: string, args: string[], extra: NodeJS.ProcessEnv): Promise<{ status: number | null; stdout: string; stderr: string; timedOut: boolean }> {
+ const { status, stdout, stderr, timedOut } = await runs.complete(root, [TSX, CLI_SOURCE, ...args], {
+ cwd: CLI_ROOT, env: envFor(root, extra), label: `harness ${args.join(' ')}`,
+ })
+ return { status, stdout, stderr, timedOut }
}
-/** The same run, without blocking this process: a test that also SERVES the CLI something (a manifest on
- * the loopback) has to keep its own event loop free while the child asks for it. */
-function runAsync(root: string, args: string[], extra: NodeJS.ProcessEnv): Promise<{ status: number | null; stdout: string; stderr: string }> {
- return new Promise((resolve) => {
- const child = spawn(process.execPath, [TSX, CLI_SOURCE, ...args], { cwd: CLI_ROOT, env: envFor(root, extra), stdio: ['ignore', 'pipe', 'pipe'] })
- let stdout = ''
- let stderr = ''
- child.stdout.on('data', (chunk: Buffer) => { stdout += chunk.toString() })
- child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString() })
- child.on('close', (status) => resolve({ status, stdout, stderr }))
- })
+function run(...args: string[]) {
+ return runAsync(freshRoot(), args, {})
}
/** A signed-in computer: `start` refuses without one, before it looks at anything else. */
@@ -123,9 +137,9 @@ describe('CLI login/start command contract', () => {
// Run in its own process group and killed as one: a dev-mode start becomes the daemon itself, and
// tsx wraps it in a child of its own.
const root = freshRoot()
- const child = spawn(process.execPath, [TSX, CLI_SOURCE, 'start'], {
+ const started = runs.start(root, [TSX, CLI_SOURCE, 'start'], {
cwd: CLI_ROOT,
- detached: true,
+ label: 'harness start (signed out)',
env: envFor(root, {
// The kernel reserves a free port atomically; a random choice can hit another test.
PORT: '0',
@@ -133,46 +147,91 @@ describe('CLI login/start command contract', () => {
// Startup's sign-in contract does not need a runtime download or the developer's Grid.
HARNESS_GRID_BIN: join(root, 'grid-unavailable'),
}),
- stdio: ['ignore', 'pipe', 'pipe'],
})
- children.push(child)
- let said = ''
- child.stdout?.on('data', (chunk: Buffer) => { said += chunk.toString() })
- child.stderr?.on('data', (chunk: Buffer) => { said += chunk.toString() })
+ const said = () => started.stdout + started.stderr
const deadline = Date.now() + 25_000
- while (Date.now() < deadline && !/serving this computer only|Sign in to Harness in your browser/.test(said)) {
+ while (Date.now() < deadline && !/serving this computer only|Sign in to Harness in your browser/.test(said())) {
await new Promise((r) => setTimeout(r, 100))
}
try {
- expect(said).toContain('not signed in — serving this computer only')
- expect(said).not.toContain('Sign in to Harness in your browser')
- expect(said).not.toContain('dialing') // no backend leg is attempted without a session
+ expect(said()).toContain('not signed in — serving this computer only')
+ expect(said()).not.toContain('Sign in to Harness in your browser')
+ expect(said()).not.toContain('dialing') // no backend leg is attempted without a session
} finally {
- try { process.kill(-child.pid!, 'SIGKILL') } catch { /* already gone */ }
+ // Running is what this start should be doing; ended here, it is not a leak.
+ await runs.end(started)
}
}, 40_000)
- it('rejects the removed join command with the two-step migration', () => {
- const result = run('join')
+ it('rejects the removed join command with the two-step migration', async () => {
+ const result = await run('join')
expect(result.status).toBe(1)
expect(result.stderr).toContain('`harness join` has been removed.')
expect(result.stderr).toContain('`harness login`, then `harness start`')
- })
+ }, 20_000)
- it('no longer has an analytics command (usage metering upload was removed)', () => {
- const result = run('analytics')
+ it('no longer has an analytics command (usage metering upload was removed)', async () => {
+ const result = await run('analytics')
expect(result.status).toBe(1)
expect(result.stderr).toContain('Unknown command: analytics')
- })
+ }, 20_000)
- it('returns a nonzero status for an unknown command', () => {
- const result = run('not-a-command')
+ it('returns a nonzero status for an unknown command', async () => {
+ const result = await run('not-a-command')
expect(result.status).toBe(1)
expect(result.stderr).toContain('Unknown command: not-a-command')
- })
+ }, 20_000)
+})
+
+describe('the processes this spec starts', () => {
+ // The guard's own test: what teardown above relies on, shown on runs built to leak. Each uses a
+ // SpawnedRuns of its own, so the leaks it makes on purpose are not this file's teardown's to report.
+ const idle = `['-e', 'setInterval(() => {}, 1000)']`
+
+ it('a run that exits leaving processes behind is caught, and teardown ends every one', async () => {
+ const guard = new SpawnedRuns((command) => command.includes('--guard-daemon'))
+ const root = freshRoot()
+ mkdirSync(join(root, 'data'), { recursive: true })
+ // Three ways a run leaves a process: a child in its group, a child in a session of its own that
+ // names the root, and a daemon in a session of its own that only the pid file names.
+ const script = `
+ const { spawn } = require('node:child_process')
+ const kept = spawn(process.execPath, ${idle}, { stdio: 'ignore' })
+ const orphan = spawn(process.execPath, [...${idle}, ${JSON.stringify(root)}], { stdio: 'ignore', detached: true })
+ const daemon = spawn(process.execPath, [...${idle}, '--', '--guard-daemon'], { stdio: 'ignore', detached: true })
+ require('node:fs').writeFileSync(${JSON.stringify(join(root, 'data', 'adapter.pid'))}, daemon.pid + '\\n')
+ console.log(JSON.stringify([kept.pid, orphan.pid, daemon.pid]))
+ for (const child of [kept, orphan, daemon]) child.unref()
+ `
+ const result = await guard.complete(root, ['-e', script], { label: 'leaky' })
+ expect(result.status, result.stderr).toBe(0)
+ const pids = JSON.parse(result.stdout) as number[]
+ expect(pids.every(alive)).toBe(true)
+ expect(guard.belonging(result.run).map((row) => row.pid).sort()).toEqual([...pids].sort())
+
+ const { leftBehind, survivors } = await guard.endAll()
+ expect(leftBehind).toHaveLength(3)
+ expect(survivors).toEqual([])
+ expect(pids.filter(alive)).toEqual([])
+ }, 30_000)
+
+ it('a run that does not end is ended at its deadline, with what it started, and is no leak', async () => {
+ const guard = new SpawnedRuns()
+ const root = freshRoot()
+ const script = `
+ const child = require('node:child_process').spawn(process.execPath, ${idle}, { stdio: 'ignore' })
+ console.log(child.pid)
+ setInterval(() => {}, 1000)
+ `
+ const result = await guard.complete(root, ['-e', script], { ms: 2_000 })
+ expect(result.timedOut).toBe(true)
+ expect(alive(Number(result.stdout.trim()))).toBe(false)
+ expect(alive(result.run.pgid)).toBe(false)
+ expect(await guard.endAll()).toEqual({ leftBehind: [], survivors: [] })
+ }, 30_000)
})
describe('start --repair beside a running daemon', () => {
diff --git a/cli/src/testing/spawnedRuns.ts b/cli/src/testing/spawnedRuns.ts
new file mode 100644
index 000000000..56762b09d
--- /dev/null
+++ b/cli/src/testing/spawnedRuns.ts
@@ -0,0 +1,202 @@
+/**
+ * Processes a test starts, and the guarantee that none of them outlives it.
+ *
+ * Why: src/cliCommand.spec.ts ran `harness start` through tsx and waited for it to exit. When a run
+ * did not exit (a start that booted a daemon instead of refusing), the test timed out, nothing killed
+ * the run, and the next one did the same: twelve `cli.ts start` processes were found orphaned nine hours
+ * later, one spinning a CPU core at 98%. Killing the direct child was never enough either: tsx runs the
+ * CLI in a child of its own, and a dev-mode start becomes the daemon, with children of its own.
+ *
+ * So every run starts as the leader of a process group of its own (`detached`), and teardown ends the
+ * whole group: SIGTERM, then SIGKILL for whatever is still there. It also ends what left the group:
+ * descendants that were still linked to a run when teardown looked, the daemon a run's pid file names,
+ * and a tmux server under the run's throwaway root (tmux daemonizes into a session of its own). What
+ * teardown had to end is reported: a run the test expected to finish that left a process behind is a
+ * leak, and the caller fails the test with it.
+ */
+import { execFileSync, spawn, type ChildProcess } from 'node:child_process'
+import { existsSync, readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+export interface Run {
+ readonly child: ChildProcess
+ /** The process group: the run's own pid, since it leads one. */
+ readonly pgid: number
+ /** The throwaway root it runs under; its pid file and tmux socket are found there. */
+ readonly root: string
+ readonly label: string
+ /** Settles when the run's own process has exited, with its status. */
+ readonly exited: Promise<number | null>
+ stdout: string
+ stderr: string
+}
+
+export interface ProcessRow { pid: number; ppid: number; pgid: number; command: string }
+
+/** Every process on the machine, as `ps` lists them (the same columns on macOS and Linux). */
+export function processTable(): ProcessRow[] {
+ const text = execFileSync('ps', ['-A', '-ww', '-o', 'pid=,ppid=,pgid=,command='], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 })
+ return text.split('\n').flatMap((line) => {
+ const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/.exec(line)
+ return match ? [{ pid: Number(match[1]), ppid: Number(match[2]), pgid: Number(match[3]), command: match[4] }] : []
+ })
+}
+
+export function alive(pid: number): boolean {
+ try { process.kill(pid, 0); return true } catch (error) { return (error as NodeJS.ErrnoException).code === 'EPERM' }
+}
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
+
+export class SpawnedRuns {
+ private readonly runs: Run[] = []
+ /** Runs the test ended or left running on purpose: what teardown finds of them is not a leak. */
+ private readonly expected = new Set<Run>()
+
+ /**
+ * [isDaemon] says whether the process a run's pid file names is the daemon that run started (the
+ * CLI's own command line, for src/cliCommand.spec.ts): a pid file can outlive its process, and the
+ * number can be somebody else's by then.
+ */
+ constructor(private readonly isDaemon: (command: string, run: Run) => boolean = () => false) {}
+
+ /** Start `node [argv]` as the leader of a new process group, under [root]. */
+ start(root: string, argv: string[], options: { env?: NodeJS.ProcessEnv; cwd?: string; label?: string } = {}): Run {
+ const child = spawn(process.execPath, argv, { cwd: options.cwd, env: options.env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] })
+ const run: Run = {
+ child, pgid: child.pid ?? -1, root, label: options.label ?? argv.join(' ').slice(0, 120),
+ exited: new Promise((resolve) => child.once('exit', (code) => resolve(code))),
+ stdout: '', stderr: '',
+ }
+ child.stdout?.on('data', (chunk: Buffer) => { run.stdout += chunk.toString() })
+ child.stderr?.on('data', (chunk: Buffer) => { run.stderr += chunk.toString() })
+ child.once('error', () => { /* reported through `exited` never settling: teardown still ends the group */ })
+ this.runs.push(run)
+ return run
+ }
+
+ /**
+ * Start a run and wait for it to finish and close its output, at most [ms]. One that has not by then
+ * is ended, group and all, and reported as `timedOut`: a hang is a failing assertion here, never a
+ * process left for the machine.
+ */
+ async complete(root: string, argv: string[], options: { env?: NodeJS.ProcessEnv; cwd?: string; label?: string; ms?: number } = {}) {
+ const run = this.start(root, argv, options)
+ const closed = new Promise<number | null>((resolve) => run.child.once('close', (code) => resolve(code)))
+ let timer: NodeJS.Timeout | undefined
+ const deadline = new Promise<'timeout'>((resolve) => { timer = setTimeout(() => resolve('timeout'), options.ms ?? 15_000) })
+ const outcome = await Promise.race([closed, deadline])
+ clearTimeout(timer)
+ if (outcome === 'timeout') {
+ await this.end(run)
+ return { status: null, stdout: run.stdout, stderr: run.stderr, timedOut: true, run }
+ }
+ return { status: outcome, stdout: run.stdout, stderr: run.stderr, timedOut: false, run }
+ }
+
+ /** The processes that belong to [run] now: its group, its linked descendants, its daemon, its orphans. */
+ belonging(run: Run, table: ProcessRow[] = processTable()): ProcessRow[] {
+ const found = new Map<number, ProcessRow>()
+ const leaderGone = exited(run)
+ if (groupIsOurs(run, table)) {
+ for (const row of table) if (row.pgid === run.pgid) found.set(row.pid, row)
+ // Descendants that left the group (a detached spawn, setsid) while their parent was still there.
+ for (let grew = true; grew;) {
+ grew = false
+ for (const row of table) {
+ if (!found.has(row.pid) && ((!leaderGone && row.ppid === run.pgid) || found.has(row.ppid))) { found.set(row.pid, row); grew = true }
+ }
+ }
+ }
+ // The daemon the run started, by the pid file it wrote, once nothing links it to the run any more.
+ const pid = readPid(join(run.root, 'data', 'adapter.pid'))
+ const daemon = pid ? table.find((row) => row.pid === pid) : undefined
+ if (daemon && this.isDaemon(daemon.command, run)) found.set(daemon.pid, daemon)
+ // An orphan that names the run's throwaway root on its command line, whatever its group and parent
+ // now. The roots are unique temporary folders, so this never reaches another test's processes.
+ for (const row of table) if (row.command.includes(run.root)) found.set(row.pid, row)
+ found.delete(process.pid)
+ found.delete(process.ppid)
+ found.delete(1)
+ return [...found.values()]
+ }
+
+ /** End [run] now, everything that belongs to it, and count nothing of it as a leak. */
+ async end(run: Run): Promise<void> {
+ this.expected.add(run)
+ await this.terminate([run])
+ }
+
+ /**
+ * Teardown: end every run and what belongs to it. Returns what was found alive of runs the test did
+ * not end itself (`leftBehind`), and anything that would not die (`survivors`).
+ */
+ async endAll(): Promise<{ leftBehind: string[]; survivors: string[] }> {
+ const runs = this.runs.splice(0)
+ const table = processTable()
+ const leftBehind = runs.filter((run) => !this.expected.has(run)).flatMap((run) => [
+ ...this.belonging(run, table).map((row) => `${run.label}: pid ${row.pid} ${row.command.slice(0, 160)}`),
+ ...(tmuxServerRunning(run.root) ? [`${run.label}: a tmux server under ${run.root}`] : []),
+ ])
+ const survivors = await this.terminate(runs, table)
+ for (const run of runs) this.expected.delete(run)
+ return { leftBehind, survivors }
+ }
+
+ /** SIGKILL every group, at once and synchronously: for a worker on its way out. */
+ killAllSync(): void {
+ for (const run of this.runs) if (!exited(run)) { try { process.kill(-run.pgid, 'SIGKILL') } catch { /* gone */ } }
+ }
+
+ private async terminate(runs: Run[], table: ProcessRow[] = processTable()): Promise<string[]> {
+ const rows = runs.flatMap((run) => this.belonging(run, table))
+ const groups = runs.filter((run) => groupIsOurs(run, table))
+ const signal = (name: NodeJS.Signals) => {
+ for (const run of groups) { try { process.kill(-run.pgid, name) } catch { /* group empty */ } }
+ for (const row of rows) { try { process.kill(row.pid, name) } catch { /* gone */ } }
+ }
+ signal('SIGTERM')
+ const gone = async (ms: number) => {
+ const deadline = Date.now() + ms
+ while (Date.now() < deadline && rows.some((row) => alive(row.pid))) await sleep(50)
+ }
+ await gone(3_000)
+ signal('SIGKILL')
+ await gone(3_000)
+ // A tmux server daemonizes into a session of its own; it is found by the socket under the root.
+ for (const run of runs) killTmuxServer(run.root)
+ return rows.filter((row) => alive(row.pid)).map((row) => `pid ${row.pid} ${row.command.slice(0, 160)}`)
+ }
+}
+
+const exited = (run: Run): boolean => run.child.exitCode !== null || run.child.signalCode !== null
+
+/**
+ * Whether the run's process group number still names its group. While any process is in a group, no
+ * new process can be given that number; once the run's own process has exited, a process with its pid
+ * is a stranger leading a group of its own, and the run's group is empty.
+ */
+function groupIsOurs(run: Run, table: ProcessRow[]): boolean {
+ return run.pgid > 1 && !(exited(run) && table.some((row) => row.pid === run.pgid))
+}
+
+function readPid(file: string): number | null {
+ try {
+ const pid = Number.parseInt(readFileSync(file, 'utf8').trim(), 10)
+ return Number.isSafeInteger(pid) && pid > 1 ? pid : null
+ } catch { return null }
+}
+
+/** The socket a tmux server started by a run would listen on: the run's TMUX_TMPDIR is its root. */
+const tmuxSocket = (root: string) => join(root, `tmux-${process.getuid?.() ?? 0}`, 'default')
+
+function tmuxServerRunning(root: string): boolean {
+ if (!existsSync(tmuxSocket(root))) return false
+ try { execFileSync('tmux', ['-S', tmuxSocket(root), 'list-sessions'], { stdio: 'ignore', timeout: 5_000 }); return true } catch { return false }
+}
+
+/** Stop a tmux server whose socket is under [root], if a run started one. */
+function killTmuxServer(root: string): void {
+ if (!existsSync(tmuxSocket(root))) return
+ try { execFileSync('tmux', ['-S', tmuxSocket(root), 'kill-server'], { stdio: 'ignore', timeout: 5_000 }) } catch { /* not running */ }
+}