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
test(runners): a runner round trip fails by name past its deadline [C7]
Corey Olson3927c744e7e2
diff --git a/test/fixture-child.js b/test/fixture-child.jsindex a9cf36c7..203d0f11 100644--- a/test/fixture-child.js+++ b/test/fixture-child.js@@ -65,7 +65,10 @@ export function runFixtureChild(command, args = [], options = {}) {return { ...result, stderr: stderrIgnored ? null : result.stderr, command: [command, ...args], elapsedMs, context, failure };}-/** Run an async fixture child, retaining redacted diagnostics without imposing a child clock. */+/**+ * Run an async fixture child, retaining redacted diagnostics without imposing a child clock.+ * The returned promise carries the spawned process as `.child`, so a caller can stop it.+ */export function runFixtureChildAsync(command, args, options = {}) {const { onStderrChunk, ...spawnOptions } = options;const started = performance.now();@@ -73,7 +76,7 @@ export function runFixtureChildAsync(command, args, options = {}) {activeFixtureChildren.add(child);let stdout = '';let rawStderr = '';- return new Promise((resolveResult) => {+ const result = new Promise((resolveResult) => {child.stdout.setEncoding('utf8').on('data', (part) => { stdout += part; });child.stderr.setEncoding('utf8').on('data', (part) => {rawStderr += part;@@ -102,6 +105,8 @@ export function runFixtureChildAsync(command, args, options = {}) {resolveResult({ status, signal, stdout, stderr, elapsedMs, context, failure, error: spawnError });});});+ result.child = child;+ return result;}/** Stop only fixture children still alive when their owning test file has finished. */diff --git a/test/runners.test.js b/test/runners.test.jsindex f3bfcb89..bd391f13 100644--- a/test/runners.test.js+++ b/test/runners.test.js@@ -10,7 +10,7 @@ import { pathToFileURL } from 'node:url';import { after, test } from 'node:test';import { listResources, takeResource } from '../src/resources.js';import { listResources as listPreRunnerResources, takeResource as takePreRunnerResource } from './fixtures/resources-pre-runners.js';-import { runFixtureChild, startFixtureChild } from './fixture-child.js';+import { runFixtureChild, runFixtureChildAsync, startFixtureChild } from './fixture-child.js';const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');const TEMP = [];@@ -77,8 +77,12 @@ function cli(repo, env, ...args) {return runFixtureChild(process.execPath, [BIN, ...args], { cwd: repo, env, encoding: 'utf8' });}-/** Make a local ssh stand-in that executes the actual worker command in a second private machine. */-function installSshStandIn({ bin, worker, home, machineHome, requests, starts, nodeCommand = 'node', dropFirst = false, dropAfterMarker }) {+/**+ * Make a local ssh stand-in that executes the actual worker command in a second private machine.+ * It appends "dispatched" and "returned" to <requests>.phases so a round trip can be timed by phase,+ * and `hold` ('dispatch', 'run' or 'return') keeps it alive at that phase, as a stuck runner would.+ */+function installSshStandIn({ bin, worker, home, machineHome, requests, starts, nodeCommand = 'node', dropFirst = false, dropAfterMarker, hold = '' }) {const ssh = join(bin, 'ssh');const source = `#!/usr/bin/env nodeimport { appendFileSync, existsSync, readFileSync, watch, writeFileSync } from 'node:fs';@@ -136,6 +140,12 @@ if (host !== ${JSON.stringify(HOST)} && host !== ${JSON.stringify(`${HOST}-drop`record({ refused: true, stdinBytes }); process.exit(255);}if (starts) appendFileSync(starts, JSON.stringify({ call, host }) + '\\n');+const phases = requests + '.phases';+const hold = ${JSON.stringify(hold)};+const holdHere = () => new Promise(() => { setInterval(() => {}, 60_000); });+if (hold === 'dispatch') await holdHere();+appendFileSync(phases, 'dispatched\\n');+if (hold === 'run') await holdHere();${dropFirst ? `if (host.endsWith('-drop') && call === 1) {process.stdin.once('data', () => {record({ dropped: true, stdinBytes, stdinSha256: stdinHash.digest('hex') }); process.exit(255);@@ -162,6 +172,8 @@ ${dropFirst ? `if (host.endsWith('-drop') && call === 1) {}child.once('error', error => { record({ spawnError: error.code ?? error.name, stdinBytes }); process.exitCode = 255; });child.once('close', (code, signal) => {+ appendFileSync(phases, 'returned\\n');+ if (hold === 'return') setInterval(() => {}, 60_000);cancelDropWait();record({ workerStarted: true, code, signal, stdinBytes, stdinSha256: stdinHash.digest('hex'),droppedAfterSetup,@@ -313,8 +325,61 @@ function startToolingCli(repo, env, args, { toolingRoot = resolve(import.meta.di}}-/** Run a gate command through its real lease and return the profile/result emitted by the API child. */-function runThroughGate(repo, env, command, { browser = true, item = '663', kind = 'check', landing = false, toolingRoot = resolve(import.meta.dirname, '..'), timeout } = {}) {+/** Per-phase deadlines for one runner round trip; together they stay near the 60-second hang ceiling. */+const ROUND_TRIP_DEADLINES = { dispatch: 20_000, 'remote run': 30_000, 'result return': 10_000 }; // budget: a stuck runner fails by name in about a minute, far under the 660-second per-test limit.++/** Count the stand-in's phase markers; a missing file means nothing was dispatched yet. */+function phaseCounts(file) {+ const lines = existsSync(file) ? readFileSync(file, 'utf8').split('\n') : [];+ return { dispatched: lines.filter(line => line === 'dispatched').length, returned: lines.filter(line => line === 'returned').length };+}++/** Stop a detached fixture child's whole process group, escalating if TERM is ignored. */+async function stopGroup(child, closed) {+ const signal = name => { try { process.kill(-child.pid, name); } catch (error) { if (error.code !== 'ESRCH') throw error; } };+ signal('SIGTERM');+ const settled = await Promise.race([closed.then(() => true), new Promise(resolve => setTimeout(() => resolve(false), 5_000))]); // budget: TERM grace before KILL.+ signal('SIGKILL');+ if (!settled) await closed;+}++/**+ * Wait for a runner round trip phase by phase: dispatch (until the stand-in is reached), remote run+ * (until the worker returns) and result return (until the controller exits). A phase past its+ * deadline stops the whole controller group and throws an error naming that phase, so a stuck+ * runner fails the test in about a minute instead of holding it to the per-test limit.+ */+async function awaitRoundTrip(child, closed, phasesFile, deadlines = ROUND_TRIP_DEADLINES) {+ const limits = { ...ROUND_TRIP_DEADLINES, ...deadlines };+ let done = null;+ closed.then(result => { done = result; });+ const timings = [];+ // The marker file may already hold earlier round trips of the same fixture; count only this one.+ const before = phasesFile ? phaseCounts(phasesFile) : { dispatched: 0, returned: 0 };+ let phase = 'dispatch';+ let phaseStarted = Date.now();+ while (!done) {+ const total = phasesFile ? phaseCounts(phasesFile) : before;+ const counts = { dispatched: total.dispatched - before.dispatched, returned: total.returned - before.returned };+ const next = counts.dispatched > counts.returned ? 'remote run' : counts.dispatched > 0 ? 'result return' : 'dispatch';+ if (next !== phase) { timings.push(`${phase} ${Date.now() - phaseStarted}ms`); phase = next; phaseStarted = Date.now(); }+ const spent = Date.now() - phaseStarted;+ if (spent > limits[phase]) {+ await stopGroup(child, closed);+ throw new Error(`runner round trip stuck in phase "${phase}": no progress after ${spent} ms (deadline ${limits[phase]} ms); earlier phases: ${timings.join(', ') || 'none'}\n${fixtureResultContext(done ?? {})}`);+ }+ await Promise.race([closed, new Promise(resolve => setTimeout(resolve, 50))]); // budget: polling interval for the stand-in's phase markers.+ }+ timings.push(`${phase} ${Date.now() - phaseStarted}ms`);+ process.stderr.write(`runner round trip phases: ${timings.join(', ')}\n`);+ return done;+}++/**+ * Run a gate command through its real lease and return the profile/result emitted by the API child.+ * `requests` names the stand-in's request log, whose .phases file times the round trip by phase.+ */+async function runThroughGate(repo, env, command, { browser = true, item = '663', kind = 'check', landing = false, toolingRoot = resolve(import.meta.dirname, '..'), requests, deadlines } = {}) {const sourceRoot = realpathSync(toolingRoot);const gateUrl = pathToFileURL(join(committedToolingSnapshot(sourceRoot, env), 'src', 'gate.js')).href;const snapshot = TOOLING_SNAPSHOTS.get(sourceRoot);@@ -327,9 +392,9 @@ process.stdout.write('PULLBOARD_RUN_RESULT ' + JSON.stringify({ isGreen: result.process.exitCode = result.isGreen ? 0 : 1;`;try {- const result = runFixtureChild(process.execPath, ['--input-type=module', '-e', script], {- cwd: repo, env, encoding: 'utf8', ...(timeout === undefined ? {} : { timeout }),- });+ // Its own process group, so a stuck phase can stop the controller, the stand-in and the worker together.+ const closed = runFixtureChildAsync(process.execPath, ['--input-type=module', '-e', script], { cwd: repo, env, detached: true });+ const result = await awaitRoundTrip(closed.child, closed, requests ? `${requests}.phases` : '', deadlines);if (result.status !== 0) snapshot.retained = true;return result;} catch (error) {@@ -518,7 +583,7 @@ test('a queued run executes on a registered runner and its result comes back (hotry {held = await takeResource({ name: 'gate', capacity: 1, scope: 'machine', root: repo,agent: 'tooling-isolation-local-holder', item: 'tooling-isolation-local-holder', kind: 'force-registered-runner' });- const run = runThroughGate(repo, env, command, { item: 'tooling-isolation', toolingRoot, timeout: 20_000 }); // budget: bound a broken fixture-only remote dispatch while its local holder is occupied.+ const run = await runThroughGate(repo, env, command, { item: 'tooling-isolation', toolingRoot, requests });assert.equal(run.status, 0, fixtureResultContext(run));assert.match(run.stdout, /HOST_CHECKOUT_ISOLATED/u);const result = gateResult(run.stdout);@@ -535,8 +600,8 @@ test('a queued run executes on a registered runner and its result comes back (hoassert.equal(requestsSeen[0].host, HOST);assert.equal(requestsSeen[0].workerStarted, true);assert.equal(requestsSeen[0].code, 0);- const cliRun = observe(startToolingCli(repo, env, ['gate', '--json'], { toolingRoot, timeout: 20_000 })); // budget: bound the real fixture CLI while forcing remote admission.- const cliResult = await cliRun.closed;+ const cliRun = observe(startToolingCli(repo, env, ['gate', '--json'], { toolingRoot, detached: true }));+ const cliResult = await awaitRoundTrip(cliRun.child, cliRun.closed, `${requests}.phases`);assert.equal(cliResult.status, 0, fixtureResultContext(cliResult));assert.equal(JSON.parse(cliResult.stdout.trim()).green, true);const allRequests = readFileSync(requests, 'utf8').trim().split(/\r?\n/u).filter(Boolean).map(line => JSON.parse(line));@@ -637,7 +702,7 @@ test('a queued run executes on a registered runner and its result comes back [C7try {held = await takeResource({ name: 'gate', capacity: 1, scope: 'machine', root: repo,agent: 'fixture-local-holder', item: 'runner-local-holder', kind: 'force-registered-runner' });- const successful = runThroughGate(repo, env, 'node --test --test-reporter=tap runner-probe.test.js', { landing: true });+ const successful = await runThroughGate(repo, env, 'node --test --test-reporter=tap runner-probe.test.js', { landing: true, requests });assert.equal(successful.status, 0, fixtureResultContext(successful));assert.match(successful.stdout, /TAP version 13/);assert.match(successful.stdout, /RUNNER_FACT /);@@ -684,7 +749,7 @@ test('a queued run executes on a registered runner and its result comes back [C7assert.equal(request.localMachineHomeInSshEnv, false);assert.doesNotMatch(successful.stdout + successful.stderr, new RegExp(SECRET, 'u'));- const red = runThroughGate(repo, env, "node -e 'if (process.env.PULLBOARD_LANDING_RUN !== \"0\") process.exit(9); process.stdout.write(\"RUNNER_EXIT_7\\n\"); process.exit(7)'");+ const red = await runThroughGate(repo, env, "node -e 'if (process.env.PULLBOARD_LANDING_RUN !== \"0\") process.exit(9); process.stdout.write(\"RUNNER_EXIT_7\\n\"); process.exit(7)'", { requests });assert.equal(red.status, 1, fixtureResultContext(red));assert.match(red.stdout, /RUNNER_EXIT_7/);const redResult = gateResult(red.stdout);@@ -711,7 +776,7 @@ console.log('RUNNER_JOURNAL_FILES ' + readdirSync(journal).filter(name => /^chil`);git(repo, env, 'add', 'runner-many-journals.js');git(repo, env, 'commit', '-q', '-m', 'test: cover a bounded large runner journal');- const manyJournals = runThroughGate(repo, env, 'node runner-many-journals.js');+ const manyJournals = await runThroughGate(repo, env, 'node runner-many-journals.js', { requests });assert.equal(manyJournals.status, 0, fixtureResultContext(manyJournals));const journalCount = Number(/RUNNER_JOURNAL_FILES (\d+)/u.exec(manyJournals.stdout)?.[1]);assert.ok(journalCount > 10_000, 'the real worker saw more journal files than the old limit');@@ -725,7 +790,7 @@ console.log('RUNNER_JOURNAL_FILES ' + readdirSync(journal).filter(name => /^chilconst tagSecretAssignment = `${['RUNNER', 'FIXTURE', 'SECRET'].join('_')}=${SECRET}`;git(repo, env, 'tag', '-a', 'runner-private-tag', '-m', tagSecretAssignment, 'HEAD');- const privateTag = runThroughGate(repo, env, 'node -e "process.stdout.write(\'PRIVATE_TAG_SCAN_REACHED\\n\')"');+ const privateTag = await runThroughGate(repo, env, 'node -e "process.stdout.write(\'PRIVATE_TAG_SCAN_REACHED\\n\')"', { requests });assert.equal(privateTag.status, 1, fixtureResultContext(privateTag));assert.match(privateTag.stdout + privateTag.stderr, /RUNNER_SECRET/u);assert.doesNotMatch(privateTag.stdout + privateTag.stderr, new RegExp(SECRET, 'u'));@@ -741,7 +806,7 @@ console.log('RUNNER_JOURNAL_FILES ' + readdirSync(journal).filter(name => /^chilgit(repo, env, 'commit', '-q', '-m', 'test: remove current private file but retain history');assert.doesNotMatch(git(repo, env, 'ls-tree', '-r', '--name-only', 'HEAD'), /(?:^|\n)\.env(?:$|\n)/u);assert.equal(readFileSync(join(repo, '.env'), 'utf8'), SECRET, 'the ignored local fixture remains private');- const historicalRed = runThroughGate(repo, env, 'node -e "process.stdout.write(\'HISTORICAL_SECRET_SCAN_REACHED\\n\')"');+ const historicalRed = await runThroughGate(repo, env, 'node -e "process.stdout.write(\'HISTORICAL_SECRET_SCAN_REACHED\\n\')"', { requests });assert.equal(historicalRed.status, 1, fixtureResultContext(historicalRed));assert.match(historicalRed.stdout + historicalRed.stderr, /RUNNER_SECRET/u);assert.doesNotMatch(historicalRed.stdout + historicalRed.stderr, new RegExp(SECRET, 'u'));@@ -759,6 +824,83 @@ console.log('RUNNER_JOURNAL_FILES ' + readdirSync(journal).filter(name => /^chil}});+/** List live processes whose command line mentions a fixture directory. */+function processesUnder(dir) {+ const listed = runFixtureChild('/bin/ps', ['-axo', 'pid=,command='], { encoding: 'utf8' });+ assert.equal(listed.status, 0, listed.context);+ return listed.stdout.split('\n').filter(line => line.includes(dir) && !line.includes('/bin/ps'));+}++test('a queued runner run finishes or fails by name within its deadline [C7]', { timeout: 120_000 }, async (t) => { // budget: one real round trip plus three held phases, each stopped by its own deadline.+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-runner-deadline-')));+ t.after(() => rmSync(dir, { recursive: true, force: true }));+ const home = join(dir, 'home');+ const machineHome = join(home, '.pullboard');+ const remoteHome = join(dir, 'worker-home');+ const remoteMachineHome = join(remoteHome, '.pullboard');+ const repo = join(dir, 'repo');+ const worker = join(dir, 'second-machine');+ const bin = join(dir, 'bin');+ const requests = join(dir, 'ssh-requests.jsonl');+ for (const folder of [repo, worker, bin, home, machineHome, remoteHome, remoteMachineHome]) mkdirSync(folder, { recursive: true });+ writeFileSync(join(machineHome, 'settings.json'), JSON.stringify({ gateSlots: 1 }));+ const env = {+ ...process.env, HOME: home, PULLBOARD_HOME: home, PULLBOARD_MACHINE_HOME: machineHome,+ PATH: `${bin}:${process.env.PATH}`, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',+ GIT_AUTHOR_NAME: 'Runner Fixture', GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Runner Fixture', GIT_COMMITTER_EMAIL: '[email protected]',+ };+ const initialized = runFixtureChild('git', ['init', '-q', '-b', 'main'], { cwd: repo, env, encoding: 'utf8' });+ assert.equal(initialized.status, 0, initialized.context);+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({ gate: 'true' }));+ writeFileSync(join(repo, 'tracked.txt'), 'committed runner source\n');+ git(repo, env, 'add', 'pullboard.json', 'tracked.txt');+ git(repo, env, 'commit', '-q', '-m', 'test: prepare runner deadline fixture');+ installSshStandIn({ bin, worker, home: remoteHome, machineHome: remoteMachineHome, requests });+ const added = cli(repo, env, 'runner', 'add', HOST, '--slots', '1', '--browser', '1', '--json');+ assert.equal(added.status, 0, added.context);+ const command = `node -e ${shellQuote('process.stdout.write("ROUND_TRIP_DONE\\n")')}`;++ const previousHome = process.env.PULLBOARD_HOME;+ const previousMachineHome = process.env.PULLBOARD_MACHINE_HOME;+ process.env.PULLBOARD_HOME = home;+ process.env.PULLBOARD_MACHINE_HOME = machineHome;+ let held;+ try {+ // Fill the controller's own gate so every run below goes to the runner.+ held = await takeResource({ name: 'gate', capacity: 1, scope: 'machine', root: repo,+ agent: 'fixture-local-holder', item: 'local-holder', kind: 'force-registered-runner' });++ // The real round trip still passes inside its deadlines.+ const real = await runThroughGate(repo, env, command, { item: 'deadline-real', requests });+ assert.equal(real.status, 0, fixtureResultContext(real));+ assert.match(real.stdout, /ROUND_TRIP_DONE/u);+ assert.equal(gateResult(real.stdout).runner, HOST);+ assert.deepEqual(phaseCounts(`${requests}.phases`), { dispatched: 1, returned: 1 });++ /** Hold the fake runner at one phase and expect the round trip to fail naming it, in time. */+ const heldAt = async (hold, phase, deadlines, ceiling) => {+ installSshStandIn({ bin, worker, home: remoteHome, machineHome: remoteMachineHome, requests, hold });+ const started = Date.now();+ await assert.rejects(runThroughGate(repo, env, command, { item: `deadline-${hold}`, requests, deadlines }),+ new RegExp(`runner round trip stuck in phase "${phase}"`, 'u'), `a runner held at ${hold} fails naming the ${phase} phase`);+ const elapsed = Date.now() - started;+ assert.ok(elapsed < ceiling, `the ${phase} failure arrives in ${elapsed} ms, under ${ceiling} ms`);+ assert.deepEqual(processesUnder(dir), [], `nothing from the held ${phase} round trip keeps running`);+ };+ // With the default deadlines a runner that never answers fails by name within about a minute.+ await heldAt('run', 'remote run', undefined, 60_000);+ await heldAt('dispatch', 'dispatch', { dispatch: 3_000 }, 15_000);+ await heldAt('return', 'result return', { 'result return': 3_000 }, 15_000);+ } finally {+ held?.release();+ if (previousHome === undefined) delete process.env.PULLBOARD_HOME;+ else process.env.PULLBOARD_HOME = previousHome;+ if (previousMachineHome === undefined) delete process.env.PULLBOARD_MACHINE_HOME;+ else process.env.PULLBOARD_MACHINE_HOME = previousMachineHome;+ }+});+test('a queued run executes on a registered runner and its result comes back [C7] (dropped runner returns ticket before later work)', async (t) => {const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-runner-retry-')));t.after(() => rmSync(dir, { recursive: true, force: true }));@@ -1081,7 +1223,7 @@ appendFileSync(${JSON.stringify(installWitnesses)}, 'postinstall\\n');git(repo, env, 'commit', '-q', '-m', 'test: assert cache symlink stays job-local');const cacheCommit = git(repo, env, 'rev-parse', 'HEAD');const cacheTree = git(repo, env, 'rev-parse', 'HEAD^{tree}');- const first = runThroughGate(repo, env, command, { item: 'cache-first' });+ const first = await runThroughGate(repo, env, command, { item: 'cache-first', requests });assert.equal(first.status, 0, fixtureResultContext(first));const firstFact = JSON.parse(/RUNNER_CACHE_FACT (\{[^\n]+\})/u.exec(first.stdout)?.[1] ?? 'null');assert.equal(firstFact.commit, cacheCommit);@@ -1093,7 +1235,7 @@ appendFileSync(${JSON.stringify(installWitnesses)}, 'postinstall\\n');assert.equal(firstFact.generatedRoot, firstFact.root, 'the first fresh checkout ran root prepare');assert.equal(readFileSync(installWitnesses, 'utf8'), 'postinstall\n', 'the first fresh checkout runs the committed workspace postinstall');- const second = runThroughGate(repo, env, command, { item: 'cache-second' });+ const second = await runThroughGate(repo, env, command, { item: 'cache-second', requests });assert.equal(second.status, 0, fixtureResultContext(second));const secondFact = JSON.parse(/RUNNER_CACHE_FACT (\{[^\n]+\})/u.exec(second.stdout)?.[1] ?? 'null');assert.equal(secondFact.commit, cacheCommit);