Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(minions): shell jobs run in their own process group and are reaped by liveness (#5062)
time-attackd6b5e268dc38
diff --git a/src/core/minions/handlers/shell.ts b/src/core/minions/handlers/shell.tsindex 223f2190d6..781cc4654e 100644--- a/src/core/minions/handlers/shell.ts+++ b/src/core/minions/handlers/shell.ts@@ -34,6 +34,7 @@ import { deriveEnvKey, resolveInheritValue } from './shell-inherit.ts';import { validateShellJobParams } from './shell-validate.ts';import { redactSecretsInText } from './shell-redact.ts';import { loadConfig } from '../../config.ts';+import { killProcessGroup, processGroupAlive } from '../job-isolation.ts';/** Environment variables passed through to shell children by default. Callers* that need additional keys (e.g. a specific API token for a cron) must name@@ -202,6 +203,27 @@ class TailBuffer {}}+/** Poll `alive` every 50ms for up to `ms`; true once it reports dead. */+async function waitUntilGone(alive: () => boolean, ms: number): Promise<boolean> {+ const deadline = Date.now() + ms;+ while (alive()) {+ if (Date.now() >= deadline) return false;+ await new Promise((resolve) => setTimeout(resolve, 50));+ }+ return true;+}++/** SIGTERM what is left, escalate to SIGKILL after the grace window by+ * liveness, then wait for the kernel to confirm termination (bounded). */+async function reapTree(alive: () => boolean, signal: (s: 'SIGTERM' | 'SIGKILL') => void): Promise<void> {+ if (!alive()) return;+ signal('SIGTERM');+ if (await waitUntilGone(alive, KILL_GRACE_MS)) return;+ signal('SIGKILL');+ if (await waitUntilGone(alive, KILL_GRACE_MS)) return;+ console.warn('[shell] job process group still present after SIGKILL; giving up the wait');+}+/** The shell handler itself. */export async function shellHandler(ctx: MinionJobContext): Promise<ShellJobResult> {if (process.env.GBRAIN_ALLOW_SHELL_JOBS !== '1') {@@ -242,6 +264,10 @@ export async function shellHandler(ctx: MinionJobContext): Promise<ShellJobResulconst startedAt = Date.now();+ // #5062: on POSIX the job runs in its own process group, so termination+ // reaches every descendant (a shell's children and grandchildren), not+ // only the direct child. Windows keeps the direct-child kill path.+ const ownGroup = process.platform !== 'win32';let proc: ChildProcess;try {if (params.cmd) {@@ -251,6 +277,7 @@ export async function shellHandler(ctx: MinionJobContext): Promise<ShellJobResulcwd: params.cwd,env,stdio: ['ignore', 'pipe', 'pipe'],+ detached: ownGroup,});} else {const argv = params.argv!;@@ -258,6 +285,7 @@ export async function shellHandler(ctx: MinionJobContext): Promise<ShellJobResulcwd: params.cwd,env,stdio: ['ignore', 'pipe', 'pipe'],+ detached: ownGroup,});}} catch (err) {@@ -267,6 +295,17 @@ export async function shellHandler(ctx: MinionJobContext): Promise<ShellJobResul}const pid = proc.pid ?? -1;+ const pgid = ownGroup && pid > 1 ? pid : null;+ const treeAlive = (): boolean => pgid !== null+ ? processGroupAlive(pgid)+ : pid > 0 && proc.exitCode === null && proc.signalCode === null;+ const signalTree = (signal: 'SIGTERM' | 'SIGKILL'): void => {+ if (pgid !== null) {+ killProcessGroup(pgid, signal);+ return;+ }+ try { proc.kill(signal); } catch { /* proc already exited */ }+ };const stdoutTail = new TailBuffer(STDOUT_TAIL_MAX_BYTES);const stderrTail = new TailBuffer(STDERR_TAIL_MAX_BYTES);@@ -282,13 +321,9 @@ export async function shellHandler(ctx: MinionJobContext): Promise<ShellJobResulconst onAbort = (label: string) => () => {if (killTimer !== null) return; // already startedkillReason = label;- if (!proc.killed) {- try { proc.kill('SIGTERM'); } catch { /* proc already exited */ }- }+ signalTree('SIGTERM');killTimer = setTimeout(() => {- if (!proc.killed) {- try { proc.kill('SIGKILL'); } catch { /* already exited */ }- }+ if (treeAlive()) signalTree('SIGKILL');}, KILL_GRACE_MS);};const sigAbort = onAbort('signal');@@ -312,10 +347,14 @@ export async function shellHandler(ctx: MinionJobContext): Promise<ShellJobResulelse if (signal === 'SIGKILL') resolve(137);else resolve(-1);});- }).finally(() => {+ }).finally(async () => {if (killTimer !== null) clearTimeout(killTimer);ctx.signal.removeEventListener('abort', sigAbort);ctx.shutdownSignal.removeEventListener('abort', shutdownAbort);+ // #5062: the job is over once its leader exits; anything it left in its+ // process group (a backgrounded child, a grandchild that ignored+ // SIGTERM) is terminated and confirmed gone before the job settles.+ await reapTree(treeAlive, signalTree);});const duration_ms = Date.now() - startedAt;diff --git a/src/core/minions/job-isolation.ts b/src/core/minions/job-isolation.tsindex 273ab1326f..4730258bfe 100644--- a/src/core/minions/job-isolation.ts+++ b/src/core/minions/job-isolation.ts@@ -455,6 +455,29 @@ export function killProcessGroup(pid: number, signal: 'SIGTERM' | 'SIGKILL'): bo}}+/**+ * #5062: does any process remain in group `pgid`? Liveness, not+ * `ChildProcess.killed` (which flips as soon as a signal is SENT), drives+ * SIGTERM→SIGKILL escalation and confirmed termination. Same /bin/kill+ * fallback as killProcessGroup for runtimes that reject negative pids.+ */+export function processGroupAlive(pgid: number): boolean {+ if (!Number.isInteger(pgid) || pgid <= 1) return false;+ try {+ process.kill(-pgid, 0);+ return true;+ } catch (e) {+ const code = (e as NodeJS.ErrnoException).code;+ if (code === 'ESRCH') return false;+ if (code === 'EPERM') return true;+ try {+ return spawnSync('/bin/kill', ['-s', '0', '--', `-${pgid}`], { stdio: 'ignore' }).status === 0;+ } catch {+ return false;+ }+ }+}+export function observeTiniChildProcessGroups(pid: number, groups: Set<number>): void {if (process.platform !== 'linux' || !Number.isInteger(pid) || pid <= 1) return;try {diff --git a/test/minions-shell-process-tree.test.ts b/test/minions-shell-process-tree.test.tsnew file mode 100644index 0000000000..26351c2608--- /dev/null+++ b/test/minions-shell-process-tree.test.ts@@ -0,0 +1,115 @@+/**+ * #5062 (fix wave 9) — the shell handler terminates the job's whole process+ * tree, with real processes.+ *+ * Pre-fix the handler signalled only its direct child and gated the SIGKILL+ * escalation on `proc.killed`, which flips true as soon as SIGTERM is SENT:+ * a child that ignored SIGTERM was never killed (the job hung until its+ * leader exited), and a grandchild outlived the job, orphaned to PID 1.+ */++import { describe, test, expect, afterEach } from 'bun:test';+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { MinionJobContext } from '../src/core/minions/types.ts';+import { shellHandler } from '../src/core/minions/handlers/shell.ts';+import { withEnv } from './helpers/with-env.ts';++const describePosix = process.platform === 'win32' ? describe.skip : describe;++function makeCtx(data: Record<string, unknown>, signal: AbortSignal): MinionJobContext {+ return {+ id: 1,+ name: 'shell',+ data,+ attempts_made: 0,+ signal,+ deadlineAtMs: null,+ shutdownSignal: new AbortController().signal,+ updateProgress: async () => {},+ updateTokens: async () => {},+ log: async () => {},+ isActive: async () => true,+ readInbox: async () => [],+ };+}++function alive(pid: number): boolean {+ try { process.kill(pid, 0); return true; } catch { return false; }+}++async function waitForFiles(paths: string[], ms = 10_000): Promise<void> {+ const deadline = Date.now() + ms;+ while (!paths.every(existsSync)) {+ if (Date.now() > deadline) throw new Error(`timed out waiting for ${paths.join(', ')}`);+ await new Promise(r => setTimeout(r, 25));+ }+}++const pid = (path: string) => Number(readFileSync(path, 'utf8').trim());+const dirs: string[] = [];+const leftovers: number[] = [];+afterEach(() => {+ for (const p of leftovers.splice(0)) { try { process.kill(p, 'SIGKILL'); } catch { /* gone */ } }+ for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });+});+function scratch(): string {+ const d = mkdtempSync(join(tmpdir(), 'shell-tree-'));+ dirs.push(d);+ return d;+}++describePosix('#5062 shell handler process tree', () => {+ test('abort kills a leader and grandchild that both ignore SIGTERM (escalates by liveness)', async () => {+ const d = scratch();+ const cmd = [+ `sh -c 'trap "" TERM; echo $$ > ${d}/grandchild.pid; exec sleep 20' &`,+ `echo $$ > ${d}/leader.pid`,+ 'trap "" TERM',+ 'sleep 21',+ ].join('\n');+ await withEnv({ GBRAIN_ALLOW_SHELL_JOBS: '1' }, async () => {+ const ac = new AbortController();+ const run = shellHandler(makeCtx({ cmd, cwd: d }, ac.signal));+ await waitForFiles([`${d}/leader.pid`, `${d}/grandchild.pid`]);+ const tree = [pid(`${d}/leader.pid`), pid(`${d}/grandchild.pid`)];+ leftovers.push(...tree);+ ac.abort(new Error('cancel'));+ await expect(run).rejects.toThrow(/aborted/);+ expect(tree.filter(alive)).toEqual([]);+ });+ }, 15_000);++ test('abort kills a grandchild that ignores SIGTERM even when the leader dies at once', async () => {+ const d = scratch();+ const cmd = [+ `sh -c 'trap "" TERM; echo $$ > ${d}/grandchild.pid; exec sleep 20' &`,+ `echo $$ > ${d}/leader.pid`,+ 'sleep 21',+ ].join('\n');+ await withEnv({ GBRAIN_ALLOW_SHELL_JOBS: '1' }, async () => {+ const ac = new AbortController();+ const run = shellHandler(makeCtx({ cmd, cwd: d }, ac.signal));+ await waitForFiles([`${d}/leader.pid`, `${d}/grandchild.pid`]);+ const grandchild = pid(`${d}/grandchild.pid`);+ leftovers.push(grandchild);+ ac.abort(new Error('cancel'));+ await expect(run).rejects.toThrow(/aborted/);+ expect(alive(grandchild)).toBe(false);+ });+ }, 15_000);++ test('a leader that exits before its descendant: the job settles only after the descendant is gone', async () => {+ const d = scratch();+ const cmd = `sleep 20 &\necho $! > ${d}/bg.pid\necho done`;+ await withEnv({ GBRAIN_ALLOW_SHELL_JOBS: '1' }, async () => {+ const result = await shellHandler(makeCtx({ cmd, cwd: d }, new AbortController().signal)) as { exit_code: number; stdout_tail: string };+ const bg = pid(`${d}/bg.pid`);+ leftovers.push(bg);+ expect(result.exit_code).toBe(0);+ expect(result.stdout_tail).toBe('done\n');+ expect(alive(bg)).toBe(false);+ });+ }, 15_000);+});