diff --git a/apps/host/server/agent/custom-command-run.mjs b/apps/host/server/agent/custom-command-run.mjs index 5543b38fbf..a54f70a5f5 100644 --- a/apps/host/server/agent/custom-command-run.mjs +++ b/apps/host/server/agent/custom-command-run.mjs @@ -11,6 +11,7 @@ * timeoutSec the time allowed, 1 to 3600 (default 120). A command that runs over is ended together with the programs it started. */ import { spawn, spawnSync } from 'node:child_process'; +import { endTree as endTreeNow, ownGroup } from '../process-tree.mjs'; import { existsSync, statSync } from 'node:fs'; import { homedir } from 'node:os'; @@ -67,10 +68,7 @@ export const clampTimeoutSec = value => { }; function endTree(child) { - try { - if (process.platform === 'win32' && child.pid) spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, timeout: 10000 }); - else child.kill('SIGKILL'); - } catch { /* gone */ } + endTreeNow(child, 'SIGKILL'); // the command's whole process group on Linux and macOS (it is started as its own group below), taskkill /T on Windows } /** @@ -85,7 +83,7 @@ export function runCommand({ command, input = '', cwd, callCwd, shell = 'auto', const limit = clampTimeoutSec(timeoutSec); let child; try { - child = spawn(plan.file, plan.args, { shell: plan.shell, windowsHide: true, cwd: where.cwd, env: { ...process.env, STRATA_INPUT: String(input ?? '') }, stdio: ['ignore', 'pipe', 'pipe'] }); + child = spawn(plan.file, plan.args, { shell: plan.shell, windowsHide: true, detached: ownGroup(), cwd: where.cwd, env: { ...process.env, STRATA_INPUT: String(input ?? '') }, stdio: ['ignore', 'pipe', 'pipe'] }); } catch (e) { return resolve({ ok: false, text: `The command could not start in ${plan.name}: ${e.message}` }); } let text = '', cut = false, timedOut = false; const take = chunk => { if (text.length < OUT_MAX + 1) text += chunk.toString(); else cut = true; }; diff --git a/apps/host/server/process-tree.mjs b/apps/host/server/process-tree.mjs new file mode 100644 index 0000000000..70748604ff --- /dev/null +++ b/apps/host/server/process-tree.mjs @@ -0,0 +1,42 @@ +// End a program this host started together with everything that program started (#4529 #4570). +// +// Windows: `taskkill /T` walks the tree. Linux and macOS have no such call, and signalling the child alone leaves its own children running (they are +// re-parented to init). A child started with `detached: ownGroup()` leads a process group of its own, so a signal to the negative pid reaches the +// whole group and nothing else: the group is the ownership record, no other process (a same-named one included) is ever signalled by name. +import { spawnSync } from 'node:child_process'; + +/** The spawn option that makes a child lead its own process group on Linux and macOS (Windows needs none: taskkill /T). */ +export const ownGroup = () => process.platform !== 'win32'; + +/** Whether the group the child leads still has a member. */ +export function groupAlive(child) { + if (process.platform === 'win32' || !child?.pid) return false; + try { process.kill(-child.pid, 0); return true; } catch (error) { return error?.code === 'EPERM'; } +} + +/** + * Signal the child's whole tree once. A child that does not lead its own group (it was not started with ownGroup()) is signalled alone, which is what + * every caller did before. + */ +export function endTree(child, signal = 'SIGTERM') { + if (!child) return; + try { + if (process.platform === 'win32') { + if (child.pid) spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore', timeout: 10000 }); + return; + } + if (child.pid) { + try { process.kill(-child.pid, signal); return; } catch { /* no such group: it did not lead one, or it is gone */ } + } + child.kill(signal); + } catch { /* already gone */ } +} + +/** SIGTERM to the tree, then SIGKILL to whatever of its group is still there after `graceMs`. Returns the timer so a caller may clear it. */ +export function endTreeThenKill(child, graceMs = 2000) { + endTree(child, 'SIGTERM'); + if (process.platform === 'win32' || !child?.pid) return null; + const timer = setTimeout(() => { if (groupAlive(child)) endTree(child, 'SIGKILL'); }, graceMs); + timer.unref?.(); + return timer; +} diff --git a/apps/host/server/timeskip.mjs b/apps/host/server/timeskip.mjs index d9288723dc..975b09a709 100644 --- a/apps/host/server/timeskip.mjs +++ b/apps/host/server/timeskip.mjs @@ -17,7 +17,8 @@ * A run is a job, not a request: it outlives the HTTP call that started it. The endpoint returns the * run id immediately and the client follows it with `/api/timeskip/status`. */ -import { spawn, spawnSync } from 'node:child_process'; +import { spawn } from 'node:child_process'; +import { endTreeThenKill, ownGroup } from './process-tree.mjs'; import { existsSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs'; import { isAbsolute, join, relative, resolve } from 'node:path'; import { timeSkipDir } from './platform-paths.mjs'; @@ -146,10 +147,7 @@ export function timeskipRevisionMessage(request) { /** End a process and everything it started (the job, the Python it runs, the revision command and its Node). */ function killTree(child) { - try { - if (process.platform === 'win32' && child.pid) spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' }); - else child.kill('SIGTERM'); - } catch { /* already gone */ } + endTreeThenKill(child); // Windows: taskkill /T. Linux and macOS: the job leads its own process group (startDetached), so the group is ended (#4529 #4570) } /** How big a folder is, stopping early once it is clearly too big to copy for a trial. */ @@ -452,7 +450,7 @@ export function createTimeSkip({ repoRoot, python, pythonArgs = [], timeoutMs = '--attempts', String(Math.max(0, Math.min(10, Number(attempts) || 0))), '--output', 'json']; if (reviseCommand) args.push('--revise-command', reviseCommand); const child = spawn(python, [...pythonArgs, cli, ...args], { - cwd: repoRoot, windowsHide: true, env: { ...env, PYTHONUTF8: '1', PYTHONIOENCODING: 'utf-8', ...extraEnv, STRATA_TIMESKIP_DIR: root }, stdio: ['ignore', 'pipe', 'pipe'], + cwd: repoRoot, windowsHide: true, detached: ownGroup(), env: { ...env, PYTHONUTF8: '1', PYTHONIOENCODING: 'utf-8', ...extraEnv, STRATA_TIMESKIP_DIR: root }, stdio: ['ignore', 'pipe', 'pipe'], }); let out = '', err = '', closed = null; child.stdout.on('data', b => { out += b.toString(); }); diff --git a/apps/host/tests/process-tree.test.mjs b/apps/host/tests/process-tree.test.mjs new file mode 100644 index 0000000000..989339960f --- /dev/null +++ b/apps/host/tests/process-tree.test.mjs @@ -0,0 +1,58 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { endTree, endTreeThenKill, groupAlive, ownGroup } from '../server/process-tree.mjs'; +import { runCommand } from '../server/agent/custom-command-run.mjs'; + +const isWin = process.platform === 'win32'; +const alive = pid => { try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; } }; +const gone = async (pid, ms = 6000) => { for (let waited = 0; waited < ms && alive(pid); waited += 100) await new Promise(r => setTimeout(r, 100)); return !alive(pid); }; + +// A program that starts a program of its own and reports its pid, the way Stop meets a job and its revision command (#4529 #4570). +const parentScript = `const { spawn } = require('node:child_process'); const k = spawn(process.execPath, ['-e', 'setTimeout(()=>{}, 120000)'], { stdio: 'ignore' }); console.log(k.pid); setTimeout(()=>{}, 120000);`; + +async function tree() { + const child = spawn(process.execPath, ['-e', parentScript], { detached: ownGroup(), stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true }); + const kid = await new Promise(resolve => child.stdout.once('data', b => resolve(Number(String(b).trim())))); + return { child, kid }; +} + +test('endTree ends the program and the program it started, and nothing else (#4529 #4570)', async () => { + const outsider = spawn(process.execPath, ['-e', 'setTimeout(()=>{}, 120000)'], { stdio: 'ignore', windowsHide: true }); // same program, not started by the job + const { child, kid } = await tree(); + try { + assert.ok(alive(kid)); + endTree(child); + assert.ok(await gone(child.pid), 'the job survived'); + assert.ok(await gone(kid), 'what the job started survived'); + assert.ok(alive(outsider.pid), 'a process of the same program that the job did not start was ended'); + } finally { outsider.kill(); try { process.kill(kid, 'SIGKILL'); } catch { /* gone */ } child.kill('SIGKILL'); } +}); + +test('endTreeThenKill follows a TERM that is ignored with a KILL of the group', { skip: isWin && 'POSIX signals' }, async () => { + const stubborn = `const { spawn } = require('node:child_process'); process.on('SIGTERM', () => {}); const k = spawn(process.execPath, ['-e', "process.on('SIGTERM',()=>{});setTimeout(()=>{},120000)"], { stdio: 'ignore' }); console.log(k.pid); setTimeout(()=>{}, 120000);`; + const child = spawn(process.execPath, ['-e', stubborn], { detached: true, stdio: ['ignore', 'pipe', 'ignore'] }); + const kid = await new Promise(resolve => child.stdout.once('data', b => resolve(Number(String(b).trim())))); + try { + await new Promise(r => setTimeout(r, 300)); + endTreeThenKill(child, 500); + assert.ok(await gone(kid, 8000), 'the group survived SIGTERM and was not killed'); + assert.equal(groupAlive(child), false); + } finally { try { process.kill(-child.pid, 'SIGKILL'); } catch { /* gone */ } } +}); + +test('a child that leads no group of its own is still ended, alone, as before', async () => { + const child = spawn(process.execPath, ['-e', 'setTimeout(()=>{}, 120000)'], { stdio: 'ignore', windowsHide: true }); + endTree(child); + assert.ok(await gone(child.pid)); +}); + +test('a custom command that runs out of time takes the programs it started with it', { skip: isWin && 'POSIX shell' }, async () => { + const marker = `/tmp/strata-cc-${process.pid}.pid`; + const result = await runCommand({ command: `sleep 120 & echo $! > ${marker}; wait`, timeoutSec: 1 }); + assert.equal(result.ok, false); + const { readFileSync, rmSync } = await import('node:fs'); + const pid = Number(readFileSync(marker, 'utf8').trim()); + rmSync(marker, { force: true }); + assert.ok(await gone(pid), 'the command\'s own child outlived the time limit'); +});