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(runners): a refused remote setup fails the run by name [C7]
Corey Olson6e6e785f5184
diff --git a/docs/api.md b/docs/api.mdindex 49c927ae..82f950ff 100644--- a/docs/api.md+++ b/docs/api.md@@ -329,3 +329,5 @@ Runner storage keeps one repository object cache and creates an isolated checkouEach checkout with a committed npm lockfile runs `npm ci`, including lifecycle scripts. Only npm's content cache is shared; installed dependencies and generated files stay in the fresh checkout. Other lock managers are refused. Combined command output and transport diagnostics are bounded at 64 MiB; exceeding that limit refuses the run.Post-run cleanup reports `RUNNER_CLEANUP_TIMEOUT` after 30 seconds instead of leaving the controller waiting indefinitely. That failure does not retry the command. The physical runner slot is released after its known children have drained and no unresolved live process remains; an unresolved live process keeps the slot occupied until cleanup can be verified.++When the runner's own resource pool refuses the run's setup, the run fails at once with `RUNNER_SETUP_REFUSED`, naming the runner host and the pool's refusal code. It is not retried, and it leaves no holder or waiter on either machine.diff --git a/src/runner-worker.js b/src/runner-worker.jsindex 7e01c2ef..06c2161c 100644--- a/src/runner-worker.js+++ b/src/runner-worker.js@@ -1094,11 +1094,29 @@ async function runCommand(spec, root, env, sink, tracker) {async function receipt(spec, fields, sink) {await flushStdout();const body = { id: spec.id, commit: spec.commit, tree: spec.tree, code: fields.code, signal: fields.signal,- runtimeSha256: spec.runtime.sha256, toolingSha256: spec.tooling.sha256, root: fields.root ?? '', outputSha256: sink.hash.digest('hex'), wallMs: Math.max(0, Date.now() - sink.wallStart) };+ runtimeSha256: spec.runtime.sha256, toolingSha256: spec.tooling.sha256, root: fields.root ?? '', outputSha256: sink.hash.digest('hex'), wallMs: Math.max(0, Date.now() - sink.wallStart),+ ...(fields.refused ? { refused: fields.refused } : {}) };const encoded = Buffer.from(JSON.stringify(body)).toString('base64');await new Promise((resolveWrite, rejectWrite) => process.stderr.write(`${RECEIPT} ${spec.id} ${encoded}\n`, error => error ? rejectWrite(error) : resolveWrite()));}+/**+ * Name the rule when the runner's own resource API refused setup. The code is a fixed identifier,+ * so it can travel to the controller where paths and runner state cannot.+ */+function setupRefusalCode(error) {+ return error?.name === 'Refused' && /^[A-Z][A-Z0-9_]{0,63}$/u.test(String(error.code ?? '')) ? error.code : '';+}++/**+ * End this worker's read of the controller's stream once nothing more will be read from it.+ * Only the history pack drains stdin to its end; a run that stops before the pack would otherwise+ * keep the worker, and so the SSH session and the run, alive after its receipt.+ */+function stopReading() {+ process.stdin.destroy();+}+/** Turn an internal setup failure into a fixed safe line rather than disclosing paths or runner state. */function safeSetupMessage(error) {const message = String(error?.message ?? '');@@ -1167,9 +1185,10 @@ async function main() {await installDependencies(root, runnerRoot, env, tracker);final = { ...(await runCommand(spec, root, { ...env, PULLBOARD_LANDING_RUN: spec.landing === true ? '1' : '0' }, sink, tracker)), root };} catch (error) {- const message = safeSetupMessage(error);+ const refused = setupRefusalCode(error);+ const message = refused ? `${safeSetupMessage(error)} [${refused}]` : safeSetupMessage(error);if (!transportLost) await sink.write(`${message}\n`);- final = { code: 1, signal: transportLost ? 'SIGHUP' : null, error: message, root: '' };+ final = { code: 1, signal: transportLost ? 'SIGHUP' : null, error: message, root: '', ...(refused ? { refused } : {}) };} finally {beginCleanup();cleanupStage = 'final descendants';@@ -1189,11 +1208,12 @@ async function main() {cleanupStage = 'job files';if (runDirectory && !cleanupTimedOut) { try { rmSync(runDirectory, { recursive: true, force: true }); } catch {} }}- if (transportLost || cleanupTimedOut) { clearTimeout(cleanupTimer); process.exitCode = 1; return; }+ if (transportLost || cleanupTimedOut) { clearTimeout(cleanupTimer); process.exitCode = 1; stopReading(); return; }cleanupStage = 'result receipt';await receipt(spec, final, sink);clearTimeout(cleanupTimer);process.exitCode = 0;+ stopReading();}main().catch(() => { process.exitCode = 1; });diff --git a/src/runners.js b/src/runners.jsindex fb169328..6fa7c69c 100644--- a/src/runners.js+++ b/src/runners.js@@ -429,6 +429,11 @@ function resultFrom(request, result) {|| receipt.outputSha256 !== createHash('sha256').update(output).digest('hex')) {throw new RunnerDropped(request.runner.host);}+ if (receipt.refused !== undefined) {+ if (typeof receipt.refused !== 'string' || !/^[A-Z][A-Z0-9_]{0,63}$/u.test(receipt.refused) || receipt.code === 0) throw new RunnerDropped(request.runner.host);+ // The runner answered, so this is a named failure, not a dropped transport to requeue.+ throw new Refused('RUNNER_SETUP_REFUSED', `runner ${request.runner.host} refused this run before it started: [${receipt.refused}] from its own resource pool; run pullboard resources and pullboard settings on ${request.runner.host} to fix that pool, then run again`);+ }return { isGreen: receipt.code === 0 && !receipt.signal, output: output.toString('utf8'),seconds: Math.round(receipt.wallMs / 1000), exitCode: receipt.code,executionRunner: request.runner.host, executionRoot: receipt.root, remoteWallMs: receipt.wallMs,diff --git a/test/machine.test.js b/test/machine.test.jsindex 985d8fc1..c1a5d84c 100644--- a/test/machine.test.js+++ b/test/machine.test.js@@ -49,6 +49,7 @@ const NOT_MOVES = {BAD_RUNNER: 'machine-wide SSH runner settings checked before remote execution',RUNNER_OUTPUT_LIMIT: 'remote execution output is bounded before accepting its result',RUNNER_CLEANUP_TIMEOUT: 'remote cleanup must report a bounded failure before returning capacity',+ RUNNER_SETUP_REFUSED: 'a runner whose own resource pool refuses setup fails the run by name instead of hanging',RUNNER_SOURCE_CHANGED: 'remote execution requires the exact admitted committed source',RUNNER_SECRET: 'source and command transfer is refused before private content leaves the machine',RUNNER_REQUEST_LIMIT: 'remote tooling requests are bounded before transport starts',diff --git a/test/runners.test.js b/test/runners.test.jsindex f3bfcb89..4eeb2f8d 100644--- a/test/runners.test.js+++ b/test/runners.test.js@@ -8,7 +8,7 @@ import { DatabaseSync } from 'node:sqlite';import { tmpdir } from 'node:os';import { pathToFileURL } from 'node:url';import { after, test } from 'node:test';-import { listResources, takeResource } from '../src/resources.js';+import { listResources, setResourceCapacity, 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';@@ -78,7 +78,7 @@ function cli(repo, env, ...args) {}/** 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 }) {+function installSshStandIn({ bin, worker, home, machineHome, requests, starts, nodeCommand = 'node', dropFirst = false, dropAfterMarker, stderrLog }) {const ssh = join(bin, 'ssh');const source = `#!/usr/bin/env nodeimport { appendFileSync, existsSync, readFileSync, watch, writeFileSync } from 'node:fs';@@ -149,7 +149,7 @@ ${dropFirst ? `if (host.endsWith('-drop') && call === 1) {stdio: ['pipe', 'pipe', 'pipe'] });child.stdout.pipe(process.stdout);child.stderr.pipe(process.stderr);- process.stdin.pipe(child.stdin);+${stderrLog ? ` child.stderr.on('data', part => appendFileSync(${JSON.stringify(stderrLog)}, part));\n` : ''} process.stdin.pipe(child.stdin);let droppedAfterSetup = false;if (dropAfterMarker) {const waiting = waitForMarker(dropAfterMarker);@@ -1259,6 +1259,106 @@ test('a queued run executes on a registered runner and its result comes back [C7}});+/** Run one action with the process's machine home pointed at another fixture machine. */+function onMachine(machineHome, action) {+ const previous = process.env.PULLBOARD_MACHINE_HOME;+ process.env.PULLBOARD_MACHINE_HOME = machineHome;+ try { return action(); }+ finally {+ if (previous === undefined) delete process.env.PULLBOARD_MACHINE_HOME;+ else process.env.PULLBOARD_MACHINE_HOME = previous;+ }+}++test('a refused remote setup fails the run by name [C7]', async (t) => {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-runner-refused-')));+ 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');+ const remoteStderr = join(dir, 'remote-stderr.log');+ const ran = join(dir, 'command-ran');+ 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 refused runner setup fixture');+ installSshStandIn({ bin, worker, home: remoteHome, machineHome: remoteMachineHome, requests, stderrLog: remoteStderr });+ const added = cli(repo, env, 'runner', 'add', HOST, '--slots', '1', '--browser', '1', '--json');+ assert.equal(added.status, 0, added.context);+ // The runner's own pool holds rows no browser gate lease can match, so the worker's request is refused.+ onMachine(remoteMachineHome, () => {+ setResourceCapacity({ name: 'gate', capacity: 1, scope: 'machine', root: repo });+ setResourceCapacity({ name: 'browser', capacity: 2, scope: 'machine', root: repo });+ });++ 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;+ let run;+ try {+ // Fill the controller's own gate so the run 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' });+ const startedAt = Date.now();+ run = observe(startQueueController(repo, env, `node -e ${shellQuote(`require('node:fs').writeFileSync(${JSON.stringify(ran)}, 'ran')`)}`,+ { item: 'refused-setup', queueMarker: null, firstItem: null }));+ const deadline = new Promise(resolve => { const timer = setTimeout(() => resolve(null), 30_000); timer.unref(); }); // budget: the bar's 30-second ceiling.+ const result = await Promise.race([run.closed, deadline]);+ assert.ok(result, 'the controller ends the refused run within 30 seconds');+ assert.ok(Date.now() - startedAt < 30_000);+ assert.notEqual(result.status, 0, 'a refused remote setup is a failed run');+ const said = `${result.stdout}${result.stderr}`;+ // Before #684 the worker's own request is refused as a capacity mismatch; after it, as a browser capacity above the gate.+ assert.match(result.stderr, new RegExp(`\\[RUNNER_SETUP_REFUSED\\] runner ${HOST} refused this run before it started: \\[(?:RESOURCE_CAPACITY_MISMATCH|BAD_BROWSER_SLOTS)\\]`, 'u'),+ `the failure names the runner host and the refusal code\n${said}`);+ assert.equal(result.stdout.includes('PULLBOARD_RUN_RESULT'), false, 'the refused run reports no test result');+ assert.equal(existsSync(ran), false, 'the command never ran');++ const receipts = readFileSync(remoteStderr, 'utf8').split('\n').filter(line => line.startsWith('PULLBOARD_RUNNER_RESULT '));+ assert.equal(receipts.length, 1, 'the worker writes one result receipt');+ const ended = readFileSync(requests, 'utf8').trim().split('\n').map(line => JSON.parse(line));+ assert.equal(ended.length, 1, 'the refused run is not retried on the runner');+ assert.equal(ended[0].workerStarted, true);+ assert.equal(ended[0].code, 0, 'the worker exits after its receipt');++ const remote = onMachine(remoteMachineHome, () => listResources({ scope: 'machine', root: repo }));+ for (const resource of remote) {+ assert.deepEqual([resource.holders.length, resource.line.length], [0, 0], `runner pool ${resource.name} keeps no holder or waiter`);+ }+ const local = onMachine(machineHome, () => listResources({ scope: 'machine', root: repo }));+ assert.deepEqual(local.find(resource => resource.name === `runner:${HOST}`)?.holders ?? [], [], 'the runner slot is released');+ assert.deepEqual(local.find(resource => resource.name === 'gate').line, [], 'the run is not left waiting in the controller queue');+ } finally {+ held?.release();+ if (run) {+ const ceiling = new Promise(resolve => { const timer = setTimeout(resolve, 20_000); timer.unref(); }); // budget: a hung controller must not hold the test file open.+ if (!(await Promise.race([run.closed.then(() => true), ceiling]))) run.child.kill('SIGTERM');+ await run.closed;+ }+ 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] (parent death drains a detached worker descendant before releasing its lease)', async (t) => {const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-runner-parent-death-')));t.after(() => rmSync(dir, { recursive: true, force: true }));