Repository navigation
fix: exit hook runners whose parent process is gone #3814
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,103 @@ | ||
| 'use strict'; | ||
|
|
||
| /** | ||
| * Keeps a hook process from outliving the harness that started it. | ||
| * | ||
| * When Claude Code kills a hook that overran its timeout, it kills the | ||
| * process it spawned. On Windows that is the bash.exe wrapper, and the | ||
| * node.exe runner underneath survives. The runner then waits on stdin or on a | ||
| * stdout flush that never completes, and lingers for hours or days. | ||
| * | ||
| * The watchdog exits the process when either: | ||
| * - the parent that spawned it is gone (Windows: the PID no longer exists; | ||
| * POSIX: the process was re-parented), checked every few seconds, or | ||
| * - a hard deadline passes. The default sits above the longest hook timeout | ||
| * in hooks.json (300s). An earlier ECC_HOOK_DEADLINE_MS from an upstream | ||
| * bootstrap takes precedence. | ||
| * | ||
| * Timers are unref'd, so the watchdog never keeps a finished hook alive. | ||
| */ | ||
|
|
||
| const DEFAULT_HARD_DEADLINE_MS = 330000; | ||
| const PARENT_POLL_MS = 2000; | ||
|
|
||
| function isProcessAlive(pid) { | ||
| try { | ||
| process.kill(pid, 0); | ||
| return true; | ||
| } catch (error) { | ||
| // EPERM: the process exists but belongs to someone else. | ||
| return error.code === 'EPERM'; | ||
| } | ||
| } | ||
|
|
||
| function resolveDeadline(nowMs, env = process.env) { | ||
| const hardDeadline = nowMs + DEFAULT_HARD_DEADLINE_MS; | ||
| const inherited = Number(env.ECC_HOOK_DEADLINE_MS); | ||
| if (Number.isSafeInteger(inherited) && inherited > nowMs) { | ||
| return Math.min(hardDeadline, inherited); | ||
| } | ||
| return hardDeadline; | ||
| } | ||
|
|
||
| function installHookWatchdog(options = {}) { | ||
| const { | ||
| label = 'hook', | ||
| env = process.env, | ||
| now = Date.now, | ||
| getPpid = () => process.ppid, | ||
| isAlive = isProcessAlive, | ||
| exit = code => process.exit(code), | ||
| writeStderr = message => process.stderr.write(message), | ||
| pollMs = PARENT_POLL_MS, | ||
| setTimer = setTimeout, | ||
| setRepeating = setInterval, | ||
| clearTimer = clearTimeout, | ||
| clearRepeating = clearInterval, | ||
| } = options; | ||
|
|
||
| const startPpid = getPpid(); | ||
| let disarmed = false; | ||
| let deadlineTimer = null; | ||
| let parentTimer = null; | ||
|
|
||
| const disarm = () => { | ||
| disarmed = true; | ||
| if (deadlineTimer) clearTimer(deadlineTimer); | ||
| if (parentTimer) clearRepeating(parentTimer); | ||
| }; | ||
|
|
||
| const fire = reason => { | ||
| if (disarmed) return; | ||
| disarm(); | ||
| try { | ||
| writeStderr(`[Hook] watchdog: ${reason}; exiting ${label}\n`); | ||
| } catch { | ||
| // stderr may be the broken pipe that got us here | ||
| } | ||
| exit(0); | ||
| }; | ||
|
|
||
| const parentGone = () => getPpid() !== startPpid || !isAlive(startPpid); | ||
|
|
||
| const delay = Math.max(0, resolveDeadline(now(), env) - now()); | ||
| deadlineTimer = setTimer(() => fire(`deadline of ${delay}ms passed`), delay); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| if (deadlineTimer && typeof deadlineTimer.unref === 'function') deadlineTimer.unref(); | ||
|
|
||
| if (Number.isInteger(startPpid) && startPpid > 1) { | ||
| parentTimer = setRepeating(() => { | ||
| if (parentGone()) fire(`parent process ${startPpid} is gone`); | ||
| }, pollMs); | ||
| if (parentTimer && typeof parentTimer.unref === 'function') parentTimer.unref(); | ||
| } | ||
|
|
||
| return disarm; | ||
| } | ||
|
|
||
| module.exports = { | ||
| DEFAULT_HARD_DEADLINE_MS, | ||
| PARENT_POLL_MS, | ||
| installHookWatchdog, | ||
| isProcessAlive, | ||
| resolveDeadline, | ||
| }; | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -14,6 +14,7 @@ const { spawnSync } = require('child_process'); | |
| const { StringDecoder } = require('string_decoder'); | ||
| const { isHookEnabled, isDryRun } = require('../lib/hook-flags'); | ||
| const { readStdinRaw: readBoundedStdin, resolveMaxStdin } = require('./hook-input'); | ||
| const { installHookWatchdog } = require('./hook-watchdog'); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This new ArtifactsLocal validation script; upload unverified
Local original-fixture output; upload unverified
Local corrected-fixture output; upload unverified
Local source and worktree output; upload unverified
Prompt To Fix With AIThis is a comment left during a code review.
Path: scripts/hooks/run-with-flags.js
Line: 17
Comment:
**Pi tests cannot load runner**
This new `require()` breaks the Pi adapter tests. `buildEccSkeleton()` copies `run-with-flags.js` and its dependencies into a temporary package, but its file list omits `hook-watchdog.js`. The copied runner exits with `MODULE_NOT_FOUND`, leaving the suite with 30 passed and 3 failed. Adding the missing dependency to the fixture in memory makes all 33 tests pass. Include `hook-watchdog.js` in that copy list before merging.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly. |
||
| const { buildPreToolUseAdditionalContext } = require('./pretooluse-visible-output'); | ||
| const { createHookContextScanner } = require('./hook-input-limits'); | ||
|
|
||
|
|
@@ -343,6 +344,7 @@ async function main() { | |
| exitWithStdout(legacyStdout, Number.isInteger(result.status) ? result.status : 0); | ||
| } | ||
|
|
||
| installHookWatchdog({ label: 'run-with-flags' }); | ||
| main().catch(err => { | ||
| process.stderr.write(`[Hook] run-with-flags error: ${err.message}\n`); | ||
| process.exit(0); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,215 @@ | ||
| /** | ||
| * Tests for the hook watchdog: hook runners must not outlive the harness | ||
| * process that spawned them. | ||
| */ | ||
|
|
||
| 'use strict'; | ||
|
|
||
| const assert = require('assert'); | ||
| const fs = require('fs'); | ||
| const os = require('os'); | ||
| const path = require('path'); | ||
| const { spawn } = require('child_process'); | ||
| const { | ||
| DEFAULT_HARD_DEADLINE_MS, | ||
| installHookWatchdog, | ||
| isProcessAlive, | ||
| resolveDeadline, | ||
| } = require('../../scripts/hooks/hook-watchdog'); | ||
|
|
||
| const RUNNER = path.join(__dirname, '..', '..', 'scripts', 'hooks', 'run-with-flags.js'); | ||
| const ORPHAN_EXIT_BUDGET_MS = 8000; | ||
|
|
||
| async function test(name, fn) { | ||
| try { | ||
| await fn(); | ||
| console.log(` ✓ ${name}`); | ||
| return true; | ||
| } catch (error) { | ||
| console.log(` ✗ ${name}`); | ||
| console.log(` Error: ${error.message}`); | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| function fakeClock() { | ||
| const timers = []; | ||
| return { | ||
| timers, | ||
| setTimer: (fn, ms) => { const t = { fn, ms, kind: 'once', unref() {} }; timers.push(t); return t; }, | ||
| setRepeating: (fn, ms) => { const t = { fn, ms, kind: 'repeat', unref() {} }; timers.push(t); return t; }, | ||
| clearTimer: t => { t.cleared = true; }, | ||
| clearRepeating: t => { t.cleared = true; }, | ||
| }; | ||
| } | ||
|
|
||
| function harness(overrides = {}) { | ||
| const clock = fakeClock(); | ||
| const exits = []; | ||
| const messages = []; | ||
| let ppid = overrides.ppid === undefined ? 4242 : overrides.ppid; | ||
| const alive = new Set([4242]); | ||
| const disarm = installHookWatchdog({ | ||
| label: 'test hook', | ||
| env: overrides.env || {}, | ||
| now: () => 1000, | ||
| getPpid: () => ppid, | ||
| isAlive: pid => alive.has(pid), | ||
| exit: code => exits.push(code), | ||
| writeStderr: message => messages.push(message), | ||
| ...clock, | ||
| }); | ||
| return { | ||
| clock, exits, messages, disarm, alive, | ||
| setPpid: value => { ppid = value; }, | ||
| deadline: () => clock.timers.find(t => t.kind === 'once'), | ||
| poll: () => clock.timers.find(t => t.kind === 'repeat'), | ||
| }; | ||
| } | ||
|
|
||
| function waitForExit(pid, budgetMs) { | ||
| const started = Date.now(); | ||
| return new Promise(resolve => { | ||
| const check = () => { | ||
| if (!isProcessAlive(pid)) return resolve(Date.now() - started); | ||
| if (Date.now() - started > budgetMs) return resolve(null); | ||
| setTimeout(check, 100); | ||
| }; | ||
| check(); | ||
| }); | ||
| } | ||
|
|
||
| async function runTests() { | ||
| console.log('\n=== Testing hook-watchdog ===\n'); | ||
| let passed = 0; | ||
| let failed = 0; | ||
| const record = ok => (ok ? passed++ : failed++); | ||
|
|
||
| record(await test('default deadline sits above the longest hook timeout (300s)', () => { | ||
| assert.ok(DEFAULT_HARD_DEADLINE_MS > 300000); | ||
| assert.strictEqual(resolveDeadline(0, {}), DEFAULT_HARD_DEADLINE_MS); | ||
| })); | ||
|
|
||
| record(await test('an earlier inherited ECC_HOOK_DEADLINE_MS wins', () => { | ||
| assert.strictEqual(resolveDeadline(1000, { ECC_HOOK_DEADLINE_MS: '6000' }), 6000); | ||
| })); | ||
|
|
||
| record(await test('a later, past or malformed inherited deadline is ignored', () => { | ||
| const hard = 1000 + DEFAULT_HARD_DEADLINE_MS; | ||
| assert.strictEqual(resolveDeadline(1000, { ECC_HOOK_DEADLINE_MS: String(hard + 5) }), hard); | ||
| assert.strictEqual(resolveDeadline(1000, { ECC_HOOK_DEADLINE_MS: '500' }), hard); | ||
| assert.strictEqual(resolveDeadline(1000, { ECC_HOOK_DEADLINE_MS: 'soon' }), hard); | ||
| })); | ||
|
|
||
| record(await test('stays quiet while the parent is alive', () => { | ||
| const h = harness(); | ||
| h.poll().fn(); | ||
| h.poll().fn(); | ||
| assert.deepStrictEqual(h.exits, []); | ||
| })); | ||
|
|
||
| record(await test('exits 0 when the parent PID disappears (Windows orphan)', () => { | ||
| const h = harness(); | ||
| h.alive.delete(4242); | ||
| h.poll().fn(); | ||
| assert.deepStrictEqual(h.exits, [0]); | ||
| assert.match(h.messages.join(''), /parent process 4242 is gone; exiting test hook/); | ||
| })); | ||
|
|
||
| record(await test('exits 0 when the process is re-parented (POSIX orphan)', () => { | ||
| const h = harness(); | ||
| h.setPpid(1); | ||
| h.poll().fn(); | ||
| assert.deepStrictEqual(h.exits, [0]); | ||
| })); | ||
|
|
||
| record(await test('exits 0 when the hard deadline fires', () => { | ||
| const h = harness(); | ||
| assert.strictEqual(h.deadline().ms, DEFAULT_HARD_DEADLINE_MS); | ||
| h.deadline().fn(); | ||
| assert.deepStrictEqual(h.exits, [0]); | ||
| assert.match(h.messages.join(''), /deadline/); | ||
| })); | ||
|
|
||
| record(await test('fires at most once', () => { | ||
| const h = harness(); | ||
| h.alive.delete(4242); | ||
| h.poll().fn(); | ||
| h.deadline().fn(); | ||
| assert.deepStrictEqual(h.exits, [0]); | ||
| })); | ||
|
|
||
| record(await test('disarm clears both timers and suppresses exits', () => { | ||
| const h = harness(); | ||
| h.disarm(); | ||
| assert.ok(h.deadline().cleared && h.poll().cleared); | ||
| h.deadline().fn(); | ||
| assert.deepStrictEqual(h.exits, []); | ||
| })); | ||
|
|
||
| record(await test('no parent polling when started without a real parent', () => { | ||
| const h = harness({ ppid: 1 }); | ||
| assert.strictEqual(h.poll(), undefined); | ||
| })); | ||
|
|
||
| record(await test('a throwing stderr write still exits', () => { | ||
| const clock = fakeClock(); | ||
| const exits = []; | ||
| installHookWatchdog({ | ||
| env: {}, now: () => 0, getPpid: () => 1, exit: code => exits.push(code), | ||
| writeStderr: () => { throw new Error('EPIPE'); }, ...clock, | ||
| }); | ||
| clock.timers[0].fn(); | ||
| assert.deepStrictEqual(exits, [0]); | ||
| })); | ||
|
|
||
| record(await test('isProcessAlive sees this process and not a dead one', async () => { | ||
| assert.strictEqual(isProcessAlive(process.pid), true); | ||
| const child = spawn(process.execPath, ['-e', '']); | ||
| await new Promise(resolve => child.on('exit', resolve)); | ||
| assert.strictEqual(isProcessAlive(child.pid), false); | ||
| })); | ||
|
|
||
| record(await test('regression: runner waiting on stdin exits after its parent is killed', async () => { | ||
| // The wrapper plays the bash.exe that Claude Code kills on timeout. It | ||
| // starts the runner detached, because bash.exe (unlike node) does not take | ||
| // its children down with it. The runner inherits the wrapper's stdin, and a | ||
| // holder process keeps a copy of that pipe's write end, as a sibling process | ||
| // that inherited the handle would. So the runner never sees EOF, and without | ||
| // the watchdog it would wait on stdin forever. | ||
| const wrapperFile = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-watchdog-')), 'wrapper.js'); | ||
| fs.writeFileSync(wrapperFile, [ | ||
| "const { spawn } = require('child_process');", | ||
| "const runner = spawn(process.execPath, [process.argv[2], 'pre:test:watchdog', 'scripts/hooks/none.js', 'minimal'],", | ||
| " { stdio: ['inherit', 'ignore', 'ignore'], detached: true });", | ||
| "process.stdout.write(runner.pid + '\\n');", | ||
| "setInterval(() => {}, 1000);", | ||
| ].join('\n')); | ||
| const wrapper = spawn(process.execPath, [wrapperFile, RUNNER], { stdio: ['pipe', 'pipe', 'pipe'] }); | ||
| const holder = spawn(process.execPath, ['-e', `setTimeout(() => {}, ${ORPHAN_EXIT_BUDGET_MS * 2})`], | ||
| { stdio: [wrapper.stdin, 'ignore', 'ignore'] }); | ||
| let wrapperStderr = ''; | ||
| wrapper.stderr.on('data', chunk => { wrapperStderr += chunk; }); | ||
| const runnerPid = await new Promise((resolve, reject) => { | ||
| wrapper.stdout.once('data', chunk => resolve(Number(String(chunk).trim()))); | ||
| wrapper.once('error', reject); | ||
| wrapper.once('exit', code => reject(new Error(`wrapper exited early (${code}): ${wrapperStderr.trim()}`))); | ||
| }); | ||
| try { | ||
| assert.ok(isProcessAlive(runnerPid), 'runner should be running before the wrapper is killed'); | ||
| wrapper.kill('SIGKILL'); | ||
| const exitedAfter = await waitForExit(runnerPid, ORPHAN_EXIT_BUDGET_MS); | ||
|
Comment on lines
+199
to
+201
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The test kills ArtifactsAuthored runner ordering reproduction
Authored watchdog installation gate
Unmodified watchdog test failure
Wrapper killed before watchdog installation
Wrapper killed after watchdog installation
Source lines, authored harnesses, and unchanged tracked files
Prompt To Fix With AIThis is a comment left during a code review.
Path: tests/hooks/hook-watchdog.test.js
Line: 199-201
Comment:
**Test kills parent too soon**
The test kills `wrapper` before it knows the runner has installed its watchdog. Receiving the PID only proves that the process was created. On POSIX, the runner can already have parent PID 1 when the watchdog reads `process.ppid`; it then skips parent polling and remains alive beyond the eight-second assertion. The unmodified suite failed this assertion, and a controlled comparison confirmed that installing the watchdog before killing the wrapper allows exit in about two seconds. Wait for a readiness signal before killing the wrapper to fix this test failure before merging.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly. |
||
| assert.notStrictEqual(exitedAfter, null, `orphaned runner ${runnerPid} still alive after ${ORPHAN_EXIT_BUDGET_MS}ms`); | ||
| } finally { | ||
| try { process.kill(runnerPid, 'SIGKILL'); } catch { /* already gone */ } | ||
| holder.kill('SIGKILL'); | ||
| wrapper.stdin.destroy(); | ||
| fs.rmSync(path.dirname(wrapperFile), { recursive: true, force: true }); | ||
| } | ||
| })); | ||
|
|
||
| console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`); | ||
| process.exit(failed > 0 ? 1 : 0); | ||
| } | ||
|
|
||
| runTests(); | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Script executed:
Repository: affaan-m/ECC
Length of output: 6240
Script executed:
Repository: affaan-m/ECC
Length of output: 16340
Script executed:
Repository: affaan-m/ECC
Length of output: 42022
Keep an expired inherited deadline expired.
run-with-flags.jschecks for an exhausted deadline only on its legacy spawn path. Exportedrun()hooks run before that guard. If the runner starts after the lifecycle deadline, the watchdog currently replaces it with a new 330-second deadline.Use the inherited positive deadline even when it has passed, and update the fallback test.
Suggested fix