Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
fix(ci): bound test file exit and close relay listeners [C7]
Corey Olson3655822ba380
diff --git a/bin/run-tests.js b/bin/run-tests.jsindex abb02372..6f4210fe 100644--- a/bin/run-tests.js+++ b/bin/run-tests.js@@ -13,6 +13,7 @@ import { AGENT_SHELL_MARKERS, SSH_SHELL_MARKERS } from '../src/person.js';const runner = fileURLToPath(import.meta.url);export const DEFAULT_TEST_TIMEOUT_MS = 660_000;+export const DEFAULT_TEST_FILE_TIMEOUT_MS = 30_000;const watchdogSource = `const { parentPort } = require('node:worker_threads');@@ -21,10 +22,40 @@ const timers = new Map();parentPort.on('message', (message) => {if (message.type === 'stop') {const active = timers.get(message.id);- if (active) clearTimeout(active.timer);+ if (active) {+ clearTimeout(active.timer);+ if (active.probe) clearTimeout(active.probe);+ }timers.delete(message.id);return;}+ if (message.type === 'file-diagnostic-update') {+ const active = timers.get(message.id);+ if (active) {+ active.handles = message.handles;+ active.observedAt = message.observedAt;+ active.updated = true;+ }+ return;+ }+ if (message.type === 'start-file') {+ const active = { handles: message.handles, observedAt: Date.now(), updated: false, timer: null, probe: null };+ active.probe = setTimeout(() => {+ parentPort.postMessage({ type: 'file-diagnostic-request', id: message.id });+ }, Math.max(0, message.timeoutMs - 50));+ active.timer = setTimeout(() => {+ const ports = active.handles.ports.length ? active.handles.ports.join(', ') : 'none';+ const handles = active.handles.types.length ? active.handles.types.join(', ') : 'none';+ const ageMs = Date.now() - active.observedAt;+ const freshness = active.updated ? 'latest responsive snapshot' : 'fallback; main thread did not answer';+ writeSync(2, 'run-tests: test file "' + message.file + '" failed: its process did not exit within ' ++ message.timeoutMs + 'ms file-exit timeout; listening ports: ' + ports + '; live handles: ' + handles ++ '; live-handle snapshot age: ' + ageMs + 'ms (' + freshness + ')\\n');+ try { process.kill(message.pid, 'SIGKILL'); } catch { /* The timed-out test-file process already exited. */ }+ }, message.timeoutMs);+ timers.set(message.id, active);+ return;+ }if (message.type !== 'start') return;const startedAt = Date.now();const timer = setTimeout(() => {@@ -52,6 +83,34 @@ function testTimeoutMs(value = process.env.PULLBOARD_TEST_TIMEOUT_MS) {return Number(value);}+/** Read the per-file exit ceiling so a completed file cannot keep the gate open. */+function testFileTimeoutMs(value = process.env.PULLBOARD_TEST_FILE_TIMEOUT_MS) {+ if (value === undefined) return DEFAULT_TEST_FILE_TIMEOUT_MS;+ if (!/^[1-9][0-9]*$/u.test(value) || !Number.isSafeInteger(Number(value)) || Number(value) > 2_147_483_647) {+ throw new Error('PULLBOARD_TEST_FILE_TIMEOUT_MS must be a positive integer no greater than 2147483647 milliseconds');+ }+ return Number(value);+}++/** Describe listening ports and live handle types when the test-file exit ceiling expires. */+function activeHandleSummary() {+ const handles = process._getActiveHandles();+ const ports = [];+ const types = [];+ for (const handle of handles) {+ const type = handle?.constructor?.name ?? 'Unknown';+ types.push(type);+ if (typeof handle?.address !== 'function' || !handle.listening) continue;+ try {+ const address = handle.address();+ if (address && typeof address === 'object' && typeof address.port === 'number') {+ ports.push(`${address.address}:${address.port}`);+ }+ } catch { /* A handle may close while its diagnostic is collected. */ }+ }+ return { ports: [...new Set(ports)].slice(0, 20), types: [...new Set(types)].slice(0, 20) };+}+/*** Keep an independent watchdog for every active test in this test-file process.*@@ -59,8 +118,17 @@ function testTimeoutMs(value = process.env.PULLBOARD_TEST_TIMEOUT_MS) {*/function installTestWatchdog() {const timeoutMs = testTimeoutMs();+ const fileTimeoutMs = testFileTimeoutMs();const file = process.env.PULLBOARD_TEST_FILE ?? process.argv[1] ?? '<unknown test file>';const watchdog = new Worker(watchdogSource, { eval: true });+ watchdog.on('message', (message) => {+ if (message.type !== 'file-diagnostic-request') return;+ watchdog.postMessage({+ type: 'file-diagnostic-update', id: message.id,+ handles: activeHandleSummary(), observedAt: Date.now(),+ });+ });+ // Message listeners ref the worker port; unref only after installing the diagnostic listener.watchdog.unref();const activeTests = new WeakMap();let nextTestId = 0;@@ -77,9 +145,15 @@ function installTestWatchdog() {if (id !== undefined) watchdog.postMessage({ type: 'stop', id });});- after(async () => {- await watchdog.terminate();- });+ /** Arm at the first root cleanup hook so a stuck cleanup remains inside the file ceiling. */+ function armFileExitWatchdog() {+ watchdog.postMessage({+ type: 'start-file', id: `${process.pid}:file`, file,+ timeoutMs: fileTimeoutMs, pid: process.pid, handles: activeHandleSummary(),+ });+ }++ after(armFileExitWatchdog);}/** Quote a path for the private Git shim without interpreting shell metacharacters. */diff --git a/test/relay-client.test.js b/test/relay-client.test.jsindex 45a5d409..453a75be 100644--- a/test/relay-client.test.js+++ b/test/relay-client.test.js@@ -115,8 +115,11 @@ async function relayServer(t, directory, auth) {api = createRelayHandler({ directory, auth, publicOrigin: origin, pollMs: 10, maintenanceMs: 0, now: () => now });t.after(async () => {api.close();+ const closed = new Promise((ready, reject) => {+ server.close((error) => error ? reject(error) : ready());+ });server.closeAllConnections();- await new Promise((ready) => server.close(ready));+ await closed;});return { origin, calls, uploads, failMoves(value) { refuseMoves = value; }, dropNextReply({ offline = false } = {}) { loseReply = true; blockAfterDrop = offline; }, failReads(value) { refuseReads = value; }, advance(days) { now = Date.now() + days * 86400000; } };}diff --git a/test/run-tests.test.js b/test/run-tests.test.jsindex fb247895..49cbb722 100644--- a/test/run-tests.test.js+++ b/test/run-tests.test.js@@ -9,6 +9,8 @@ import { runFixtureChild } from './fixture-child.js';const runner = fileURLToPath(new URL('../bin/run-tests.js', import.meta.url));const shardFileCount = 9;+const fixtureExitCeilingMs = '500';+const fixtureCleanupMs = '100';/** Build a private runner checkout whose tests record the files Node actually selects. */function makeShardFixture(t) {@@ -88,3 +90,96 @@ function badShardTest() {}test('a bad shard is refused by name [C7]', badShardTest);++/** Build an isolated production-runner fixture with the source imports it needs. */+function makeFileExitFixture(t, source) {+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-test-file-exit-')));+ const bin = join(root, 'bin');+ const tests = join(root, 'test');+ mkdirSync(bin);+ mkdirSync(tests);+ writeFileSync(join(root, 'package.json'), JSON.stringify({ type: 'module' }));+ copyFileSync(runner, join(bin, 'run-tests.js'));+ cpSync(fileURLToPath(new URL('../src', import.meta.url)), join(root, 'src'), { recursive: true });+ const testFile = join(tests, 'file-exit.test.js');+ writeFileSync(testFile, source);+ t.after(() => rmSync(root, { recursive: true, force: true }));+ return {+ root, runner: join(bin, 'run-tests.js'), testFile,+ cleanupFile: join(root, 'cleanup.txt'), portFile: join(root, 'port.txt'),+ };+}++/** Run one fixture file with a bounded ceiling and clean up its process group if it hangs. */+function runFileExitFixture(fixture) {+ const result = runFixtureChild(process.execPath, [fixture.runner, fixture.testFile], {+ cwd: fixture.root,+ detached: true,+ encoding: 'utf8',+ env: {+ ...process.env,+ PULLBOARD_TEST_FILE_TIMEOUT_MS: fixtureExitCeilingMs,+ PULLBOARD_FILE_EXIT_CLEANUP: fixture.cleanupFile,+ PULLBOARD_FILE_EXIT_PORT: fixture.portFile,+ },+ timeout: 6_000,+ });+ if (result.error?.code === 'ETIMEDOUT' && result.pid) {+ try { process.kill(-result.pid, 'SIGKILL'); } catch { /* The owned fixture process group already exited. */ }+ }+ return result;+}++/** Combine native test output and the production runner's file-exit diagnostic. */+function outputOf(result) {+ return `${result.stdout ?? ''}${result.stderr ?? ''}`;+}++test('a test file that won\'t exit fails by name [C7]', (t) => {+ const fixture = makeFileExitFixture(t, `import { createServer } from 'node:http';+import { writeFileSync } from 'node:fs';+import { after, test } from 'node:test';+const server = createServer((_request, response) => response.end('ok'));+test('leave cleanup active [C7]', () => {});+/** Open the listener only after watchdog arming, then leave the root cleanup hook stuck. */+after(async () => {+ await new Promise((ready) => server.listen(0, '127.0.0.1', ready));+ writeFileSync(process.env.PULLBOARD_FILE_EXIT_PORT, String(server.address().port));+ await new Promise(() => {});+});+`);+ const result = runFileExitFixture(fixture);+ const output = outputOf(result);+ const port = readFileSync(fixture.portFile, 'utf8').trim();+ assert.equal(result.status, 1, result.context);+ assert.ok(result.elapsedMs >= Number(fixtureExitCeilingMs), `the process remains through its ${fixtureExitCeilingMs}ms file ceiling: ${result.elapsedMs}ms`);+ assert.ok(result.elapsedMs < 5_000, `the runner terminates the stuck cleanup within the 5-second bound: ${result.elapsedMs}ms`); // budget: 500ms file ceiling plus Node startup and CI scheduling allowance.+ assert.match(output, /test file ".*file-exit\.test\.js" failed: its process did not exit within 500ms file-exit timeout/u);+ assert.match(output, /live-handle snapshot age: [0-9]+ms \((?:latest responsive snapshot|fallback; main thread did not answer)\)/u);+ assert.ok(output.includes(`127.0.0.1:${port}`), `the diagnostic names its listening port ${port}: ${output}`);+ assert.match(output, /live handles:.*Server/u);+ assert.match(output, /leave cleanup active \[C7\]/u);+});++test('a file that exits cleanly is not touched [C7]', (t) => {+ const fixture = makeFileExitFixture(t, `import { createServer } from 'node:http';+import { writeFileSync } from 'node:fs';+import { after, test } from 'node:test';+const server = createServer((_request, response) => response.end('ok'));+test('clean test file exits [C7]', () => {});+after(async () => {+ await new Promise((ready) => server.listen(0, '127.0.0.1', ready));+ writeFileSync(process.env.PULLBOARD_FILE_EXIT_PORT, String(server.address().port));+ await new Promise((ready, reject) => server.close((error) => error ? reject(error) : ready()));+ await new Promise((ready) => setTimeout(ready, ${fixtureCleanupMs}));+ writeFileSync(process.env.PULLBOARD_FILE_EXIT_CLEANUP, 'done');+});+`);+ const result = runFileExitFixture(fixture);+ const output = outputOf(result);+ assert.equal(result.status, 0, result.context);+ assert.equal(result.signal, null, 'a clean test file is never killed by the watchdog');+ assert.equal(readFileSync(fixture.cleanupFile, 'utf8'), 'done', 'asynchronous cleanup within the ceiling completes normally');+ assert.ok(readFileSync(fixture.portFile, 'utf8').trim(), 'the cleanup listener was opened after watchdog arming');+ assert.doesNotMatch(output, /file-exit timeout/u);+});