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(runner): retain cleanup failure diagnostics [C7]
Corey Olson27d09f9f369a
diff --git a/src/runner-worker.js b/src/runner-worker.jsindex 8a8c8256..2de851bd 100644--- a/src/runner-worker.js+++ b/src/runner-worker.js@@ -24,6 +24,9 @@ const CLEANUP_BUDGET_MS = 30_000;let cleanupDeadline = Infinity;let cleanupTimedOut = false;let cleanupTimer = null;+let cleanupStage = 'command exit';+let cleanupDirectory = null;+let cleanupDetails = null;/** Start the post-run budget once; later cleanup phases cannot extend it. */function beginCleanup() {@@ -37,6 +40,16 @@ function beginCleanup() {function reportCleanupTimeout() {if (cleanupTimedOut || Date.now() < cleanupDeadline) return;cleanupTimedOut = true;+ const details = { id: workerId, stage: cleanupStage, ...(cleanupDetails?.() ?? {}) };+ // A timeout may arrive after ordinary job deletion while output is still flushing.+ // Keep a small diagnostic even then; it never contains command arguments or credentials.+ if (cleanupDirectory) {+ try {+ mkdirSync(cleanupDirectory, { recursive: true, mode: 0o700 });+ writeFileSync(join(cleanupDirectory, 'cleanup-timeout.json'), JSON.stringify(details) + '\n', { mode: 0o600 });+ } catch { /* The named red result remains authoritative if diagnostic storage fails. */ }+ }+ process.stderr.write(`PULLBOARD_RUNNER_CLEANUP_UNVERIFIED ${workerId} ${details.reason || cleanupStage}\n`);process.stderr.write(`PULLBOARD_RUNNER_CLEANUP_TIMEOUT ${workerId}\n`);}@@ -658,6 +671,12 @@ function createDescendantTracker(directory) {timer.unref();return {nodeOptions: journal.nodeOptions,+ /** Describe the last observed cleanup state without treating it as a fresh ownership proof. */+ cleanupState() {+ return { reason, uncertain, censusFailure, knownCount: known.size,+ pending: [...pendingIdentities].slice(0, 16).map(([pid, identity]) => ({ pid, birth: identity.birth })),+ live: liveDescendants().slice(0, 16).map(({ pid, birth, group }) => ({ pid, birth, group })) };+ },registerRoot,stopDescendants,/** Revalidate a process group immediately before signaling; null means census ambiguity. */@@ -989,8 +1008,11 @@ async function runCommand(spec, root, env, sink, tracker) {forward(child.stdout); forward(child.stderr);const result = await closed;beginCleanup();+ cleanupStage = 'command output';await writes;+ cleanupStage = 'command descendants';await tracker.stopDescendants();+ cleanupStage = 'command process group';await drainOwned(owned);if (transportDrain) await transportDrain;if (outputError) throw outputError;@@ -1051,6 +1073,7 @@ async function main() {mkdirSync(base, { recursive: true, mode: 0o700 });chmodSync(base, 0o700);runDirectory = mkdtempSync(join(base, `${spec.id}-`));+ cleanupDirectory = runDirectory;const root = join(runDirectory, 'checkout');const privateHome = join(runDirectory, 'home');const temporary = join(runDirectory, 'tmp');@@ -1068,6 +1091,7 @@ async function main() {}, machineHomePath);const canonicalMachineHome = machineHomePath;tracker = createDescendantTracker(runDirectory);+ cleanupDetails = tracker.cleanupState;activeDescendantTracker = tracker;const env = scopedEnvironment(privateHome, temporary, canonicalMachineHome, lease, api, tracker.nodeOptions);await checkoutHistory(api, runnerRoot, root, packFile, spec, env);@@ -1079,19 +1103,25 @@ async function main() {final = { code: 1, signal: transportLost ? 'SIGHUP' : null, error: message, root: '' };} finally {beginCleanup();+ cleanupStage = 'final descendants';if (tracker) await tracker.stopDescendants();+ cleanupStage = 'final process groups';await drainAllOwned();if (tracker) {+ cleanupStage = 'final verification';await tracker.verifyAfterGroups();tracker.stopMonitoring();activeDescendantTracker = null;}if (lease) {+ cleanupStage = 'lease release';try { lease.release(); } catch { /* Retaining a lease on cleanup error is safer than speculative deletion. */ }}- if (runDirectory) { try { rmSync(runDirectory, { recursive: true, force: true }); } catch {} }+ cleanupStage = 'job files';+ if (runDirectory && !cleanupTimedOut) { try { rmSync(runDirectory, { recursive: true, force: true }); } catch {} }}if (transportLost || cleanupTimedOut) { clearTimeout(cleanupTimer); process.exitCode = 1; return; }+ cleanupStage = 'result receipt';await receipt(spec, final, sink);clearTimeout(cleanupTimer);process.exitCode = 0;diff --git a/src/runners.js b/src/runners.jsindex 44d90f1a..ef8f92e4 100644--- a/src/runners.js+++ b/src/runners.js@@ -360,7 +360,7 @@ export async function runOnRunnerAsync(root, command, options) {try {const child = spawn('ssh', request.args, { env: request.env, stdio: ['pipe', 'pipe', 'pipe'] });const output = [], diagnostics = [];- let bytes = 0, error, control = '', requested = false, transfer = null;+ let bytes = 0, error, control = '', requested = false, transfer = null, cleanupReason = '';const abort = () => { error ??= new Error('runner transport canceled'); child.stdin.destroy(); child.kill('SIGTERM'); };options.signal?.addEventListener('abort', abort, { once: true });removeAbort = () => options.signal?.removeEventListener('abort', abort);@@ -379,8 +379,10 @@ export async function runOnRunnerAsync(root, command, options) {let newline;while ((newline = control.indexOf('\n')) >= 0) {const line = control.slice(0, newline); control = control.slice(newline + 1);+ const cleanupPrefix = `PULLBOARD_RUNNER_CLEANUP_UNVERIFIED ${request.spec.id} `;+ if (line.startsWith(cleanupPrefix)) cleanupReason = line.slice(cleanupPrefix.length, cleanupPrefix.length + 240);if (line === `PULLBOARD_RUNNER_CLEANUP_TIMEOUT ${request.spec.id}`) {- error = new Refused('RUNNER_CLEANUP_TIMEOUT', `runner ${request.runner.host} could not verify cleanup within 30 seconds; inspect the runner before another run`);+ error = new Refused('RUNNER_CLEANUP_TIMEOUT', `runner ${request.runner.host} could not verify cleanup within 30 seconds${cleanupReason ? ': ' + cleanupReason : ''}; inspect job ${request.spec.id} under its runner namespace before another run`);child.stdin.destroy(); child.kill('SIGTERM'); return;}const prefix = `PULLBOARD_RUNNER_NEED ${request.spec.id} `;diff --git a/test/runners.test.js b/test/runners.test.jsindex c3207244..c778a155 100644--- a/test/runners.test.js+++ b/test/runners.test.js@@ -1,7 +1,7 @@/** Registered SSH runner execution stays inside a committed, secret-free worker checkout [C7]. */import assert from 'node:assert/strict';import { basename, dirname, join, relative, resolve, sep } from 'node:path';-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, watch, writeFileSync } from 'node:fs';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, watch, writeFileSync } from 'node:fs';import { spawn } from 'node:child_process';import { once } from 'node:events';import { DatabaseSync } from 'node:sqlite';@@ -1221,6 +1221,16 @@ console.log('RUNNER_CLEANUP_TIMEOUT_BODY_RAN');assert.equal(completed.status, 1, `${completed.stderr}\n${completed.stdout}`);const response = JSON.parse(completed.stdout.trim());assert.equal(response.error?.code, 'RUNNER_CLEANUP_TIMEOUT', JSON.stringify(response));+ assert.match(response.error.message, /child spawn journal overflow or write failure/u,+ 'the named refusal retains the worker reason instead of losing it at the controller');+ const jobId = /inspect job ([A-Za-z0-9_-]+)/u.exec(response.error.message)?.[1];+ assert.ok(jobId, 'the refusal identifies the exact failed job for inspection');+ const retained = readdirSync(join(remoteStateRoot, 'jobs')).find(name => name.startsWith(jobId + '-'));+ assert.ok(retained, 'a cleanup timeout retains its private job diagnostics');+ const diagnosis = JSON.parse(readFileSync(join(remoteStateRoot, 'jobs', retained, 'cleanup-timeout.json'), 'utf8'));+ assert.equal(diagnosis.id, jobId);+ assert.match(diagnosis.reason, /child spawn journal overflow or write failure/u);+ assert.ok(diagnosis.stage, 'the timeout records which cleanup step was running');assert.ok(existsSync(bodyRan), 'the committed command ran to completion and wrote its own overflow marker');assert.equal(readFileSync(starts, 'utf8').trim().split('\n').length, 1, 'the refused cleanup result is not retried or sent to a local runner');await waitForCondition(() => readRemoteGateHolders(remoteDatabase).length === 0,