Skip to content

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.

fix(gate): bound file and browser concurrency [C7]

Corey Olsonafa4df8bf261
diff --git a/bin/run-tests.js b/bin/run-tests.js
index 2166ff40..64e7ced9 100644
--- a/bin/run-tests.js
+++ b/bin/run-tests.js
@@ -6,6 +6,7 @@ import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:f
import { delimiter, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { execFileSync, spawnSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
import { tmpdir } from 'node:os';
import { after, afterEach, beforeEach } from 'node:test';
import { Worker } from 'node:worker_threads';
@@ -234,15 +235,32 @@ function testEnvironment(sandbox, gateMarkers = {}) {
* @param {NodeJS.ProcessEnv} env
* @returns {import('node:child_process').SpawnSyncReturns<string>}
*/
-function runTests(args, env) {
+function runTests(args, env, concurrency) {
+ let files = concurrency.files;
+ const forwarded = [];
+ for (let at = 0; at < args.length; at += 1) {
+ const argument = args[at];
+ if (argument === '--') { forwarded.push(...args.slice(at)); break; }
+ if (/^--test[-_]concurrency(?:=|$)/u.test(argument)) {
+ const value = argument.includes('=') ? argument.slice(argument.indexOf('=') + 1) : args[++at];
+ if (!/^[1-9][0-9]*$/u.test(value ?? '') || !Number.isSafeInteger(Number(value))) {
+ throw new Error('--test-concurrency must be a positive integer');
+ }
+ files = Math.min(files, Number(value));
+ } else if (/^--(?:experimental-)?test[-_]isolation(?:=none|$)/u.test(argument) &&
+ (argument.endsWith('=none') || args[at + 1] === 'none')) {
+ throw new Error('bounded browser test files require process isolation; remove --test-isolation=none');
+ } else forwarded.push(argument);
+ }
const reporter = args.some((argument) => argument === '--test-reporter' || argument.startsWith('--test-reporter='));
const nodeArgs = [
'--disable-warning=ExperimentalWarning',
'--test',
+ `--test-concurrency=${files}`,
...(!reporter ? ['--test-reporter=tap'] : []),
'--import',
runner,
- ...args,
+ ...forwarded,
];
return spawnSync(process.execPath, nodeArgs, { env, stdio: 'inherit' });
}
@@ -375,8 +393,12 @@ function shardArguments(args) {
}
/** Run tests in the disposable environment, preserving a marker only when a parent holds the slot. */
-function executeTests(args, sandbox, gateMarkers, fullSuite) {
+function executeTests(args, sandbox, gateMarkers, fullSuite, concurrency) {
const env = testEnvironment(sandbox, gateMarkers);
+ // This is an inner file limit; the real machine gate/browser lease remains unchanged.
+ env.PULLBOARD_TEST_BROWSER_RESOURCE = 'test-browser-files:' + randomUUID();
+ env.PULLBOARD_TEST_BROWSER_CAPACITY = String(concurrency.browser);
+ delete env.PULLBOARD_TEST_RUNNER_PID;
let selectedArgs = args;
if (fullSuite) {
let files;
@@ -397,7 +419,7 @@ function executeTests(args, sandbox, gateMarkers, fullSuite) {
}
if (files) selectedArgs = [...args, ...files];
}
- const result = runTests(selectedArgs, env);
+ const result = runTests(selectedArgs, env, concurrency);
if (result.error) throw result.error;
return result;
}
@@ -409,8 +431,11 @@ function executeTests(args, sandbox, gateMarkers, fullSuite) {
* @returns {Promise<void>}
*/
async function main(args) {
+ let concurrency;
try {
testTimeoutMs();
+ const { testConcurrency } = await import('../src/gate.js');
+ concurrency = testConcurrency(process.cwd());
} catch (error) {
process.stderr.write(`${error.message}\n`);
process.exitCode = 1;
@@ -434,7 +459,7 @@ async function main(args) {
const run = (gateMarkers) => {
const sandbox = mkdtempSync(join(tmpdir(), 'pullboard-test-run-'));
try {
- const result = executeTests(args, sandbox, gateMarkers, fullSuite);
+ const result = executeTests(args, sandbox, gateMarkers, fullSuite, concurrency);
signal = result.signal;
process.exitCode = result.status ?? 1;
} finally { rmSync(sandbox, { recursive: true, force: true }); }
@@ -480,5 +505,18 @@ if (process.argv[1] && resolve(process.argv[1]) === runner) {
await main(process.argv.slice(2));
} else if (process.argv[1]) {
process.env.PULLBOARD_TEST_FILE = process.argv[1];
+ if (process.env.PULLBOARD_TEST_BROWSER_RESOURCE && process.ppid === Number(process.env.PULLBOARD_TEST_RUNNER_PID)) {
+ const { testsNeedBrowser } = await import('../src/browser-admission.js');
+ if (await testsNeedBrowser(process.cwd(), [process.argv[1]])) {
+ const { takeResource } = await import('../src/resources.js');
+ const lease = await takeResource({ name: process.env.PULLBOARD_TEST_BROWSER_RESOURCE,
+ capacity: Number(process.env.PULLBOARD_TEST_BROWSER_CAPACITY), kind: 'test-browser-file', root: process.cwd() });
+ // Hold through file cleanup and process exit, including the watchdog's forced-exit path.
+ process.once('exit', () => lease.release());
+ }
+ }
installTestWatchdog();
+} else if (process.env.PULLBOARD_TEST_BROWSER_RESOURCE) {
+ // Native --test preloads this module before it creates workers. Forks inside tests do not own file slots.
+ process.env.PULLBOARD_TEST_RUNNER_PID = String(process.pid);
}
diff --git a/src/gate.js b/src/gate.js
index 765f004b..7a0f2ccd 100644
--- a/src/gate.js
+++ b/src/gate.js
@@ -8,6 +8,7 @@ import { spawn, spawnSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
+import { availableParallelism } from 'node:os';
import { gitChildEnv, gitPath, headTree, invalidateGitFacts, isClean, untracked } from './git.js';
import { secretsIn } from './hooks.js';
import { Refused } from './refused.js';
@@ -28,6 +29,36 @@ const PASSING_RE = /^\s*(ok \d+\b|# Subtest:)/;
// Lines kept under a failure, where test runners say why: the message, expected and actual.
const CONTEXT_LINES = 10;
+/** Detect the performance-core budget on Apple Silicon, or the runtime's usable CPU budget elsewhere. */
+export function performanceCores() {
+ if (process.platform === 'darwin') {
+ const result = spawnSync('/usr/sbin/sysctl', ['-n', 'hw.perflevel0.physicalcpu'], { encoding: 'utf8' });
+ const count = Number(result.stdout?.trim());
+ if (result.status === 0 && Number.isSafeInteger(count) && count > 0) return count;
+ }
+ return Math.max(1, availableParallelism());
+}
+
+/** One policy for native file concurrency and the separate per-run browser-file limit. */
+export function testConcurrency(root, cores = performanceCores()) {
+ const file = join(root, 'pullboard.json');
+ let config = {};
+ if (existsSync(file)) {
+ try { config = JSON.parse(readFileSync(file, 'utf8')); }
+ catch { throw new Refused('BAD_CONFIG', 'pullboard.json must be valid JSON before running tests'); }
+ }
+ const setting = config.testConcurrency ?? {};
+ if (!setting || typeof setting !== 'object' || Array.isArray(setting)) {
+ throw new Refused('BAD_CONFIG', 'testConcurrency must be an object with positive integer files and browser fields');
+ }
+ const files = setting.files ?? cores;
+ const browser = setting.browser ?? 2;
+ if (!Number.isSafeInteger(files) || files < 1 || !Number.isSafeInteger(browser) || browser < 1 || browser > 2) {
+ throw new Refused('BAD_CONFIG', 'testConcurrency.files must be positive; testConcurrency.browser must be 1 or 2');
+ }
+ return { files, browser: Math.min(files, browser) };
+}
+
/**
* The lines of a failure worth an agent's attention: each line that looks like a failure with the
* lines under it that say why, then the end of the output, within one cap, so a refusal or a retry
diff --git a/test/gate.test.js b/test/gate.test.js
index 479a089e..a3bb34ee 100644
--- a/test/gate.test.js
+++ b/test/gate.test.js
@@ -4,11 +4,11 @@
*/
import assert from 'node:assert/strict';
import { runFixtureExecFile as execFileSync, runFixtureChild as spawnSync, runFixtureChild, runFixtureGit } from './fixture-child.js';
-import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { cpSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { after, test } from 'node:test';
-import { digestOf } from '../src/gate.js';
+import { digestOf, testConcurrency } from '../src/gate.js';
const PRIVATE_WORKER = resolve(import.meta.dirname, '../src/private-check-worker.js');
@@ -18,6 +18,72 @@ after(() => {
for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
});
+/** Read the real file bodies' start/finish records to measure overlap without sampling process names. */
+function fileOverlap(file) {
+ const active = new Map();
+ const starts = [];
+ let files = 0, browser = 0;
+ for (const line of readFileSync(file, 'utf8').trim().split('\n')) {
+ const event = JSON.parse(line);
+ if (event.start) {
+ assert.equal(active.has(event.id), false, 'a file begins once');
+ active.set(event.id, event.browser);
+ starts.push(event.id);
+ files = Math.max(files, active.size);
+ browser = Math.max(browser, [...active.values()].filter(Boolean).length);
+ } else {
+ assert.equal(active.delete(event.id), true, 'every finish has a start');
+ }
+ }
+ assert.equal(active.size, 0, 'every selected file finishes');
+ return { files, browser, starts };
+}
+
+test('the landing gate bounds its own concurrency [C7]', () => {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-file-caps-')));
+ dirs.push(root);
+ cpSync(resolve(import.meta.dirname, '../src'), join(root, 'src'), { recursive: true });
+ mkdirSync(join(root, 'bin'));
+ cpSync(resolve(import.meta.dirname, '../bin/run-tests.js'), join(root, 'bin/run-tests.js'));
+ writeFileSync(join(root, 'package.json'), '{"type":"module"}\n');
+ const config = join(root, 'pullboard.json');
+ assert.deepEqual(testConcurrency(root, 7), { files: 7, browser: 2 }, 'the default file budget is the detected core budget');
+ const selected = [];
+ for (let id = 0; id < 9; id += 1) {
+ const browser = id < 4;
+ const folder = join(root, 'test', browser ? 'cockpit' : 'ordinary');
+ mkdirSync(folder, { recursive: true });
+ const file = join(folder, `overlap-${id}.test.js`);
+ selected.push(file);
+ writeFileSync(file, `import {appendFileSync} from 'node:fs';
+import {test} from 'node:test';
+/** Keep controlled work alive briefly so concurrent file bodies leave overlapping records. */
+test('record real file ${id} [C7]', async () => {
+ appendFileSync(process.env.PULLBOARD_CAP_CAPTURE, JSON.stringify({start:true,id:${id},browser:${browser}})+'\\n');
+ await new Promise(resolve => setTimeout(resolve, 200)); // budget: controlled fixture work, not a readiness deadline or production wait.
+ appendFileSync(process.env.PULLBOARD_CAP_CAPTURE, JSON.stringify({start:false,id:${id}})+'\\n');
+});\n`);
+ }
+ for (const setting of [{ files: 3, browser: 2 }, { files: 2, browser: 1 }]) {
+ writeFileSync(config, JSON.stringify({ testConcurrency: setting }));
+ assert.deepEqual(testConcurrency(root, 7), setting, 'pullboard.json overrides the shared policy');
+ const capture = join(root, `overlap-${setting.files}.jsonl`);
+ const result = runFixtureChild(process.execPath, [join(root, 'bin/run-tests.js'), '--test-concurrency=9', ...selected], {
+ cwd: root, env: { ...process.env, PULLBOARD_CAP_CAPTURE: capture,
+ PULLBOARD_MACHINE_HOME: join(root, `machine-${setting.files}`) }, encoding: 'utf8',
+ });
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ const peak = fileOverlap(capture);
+ assert.ok(peak.files <= setting.files, `actual file-body overlap ${peak.files} exceeds ${setting.files}`);
+ assert.ok(peak.browser <= setting.browser, `actual browser-file overlap ${peak.browser} exceeds ${setting.browser}`);
+ assert.deepEqual(peak.starts.sort((a, b) => a - b), Array.from({ length: 9 }, (_, id) => id), 'every selected file runs once');
+ assert.match(result.stdout, /# tests 9\b/);
+ assert.match(result.stdout, /# fail 0\b/);
+ }
+ writeFileSync(config, JSON.stringify({ testConcurrency: { browser: 3 } }));
+ assert.throws(() => testConcurrency(root, 7), /browser must be 1 or 2/);
+});
+
/**
* A repo whose coordinator holds item #1, with this gate. Every run of the gate first adds a line
* to runs.log beside the repo, so a test can count the runs.