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(tests): bound landing concurrency [C7,V4]

Corey Olson4ca2b2a69a70
diff --cc bin/run-tests.js
index 574c0d82,e512800b..7ffdfcef
--- a/bin/run-tests.js
+++ b/bin/run-tests.js
@@@ -261,834 -265,6 +278,845 @@@ function runTests(args, env, concurrenc
return spawnSync(process.execPath, nodeArgs, { env, stdio: 'inherit' });
}
+/** Convert the Node test CLI subset to the supported node:test run() options. */
- async function landingTestOptions(args, env) {
++async function landingTestOptions(args, env, concurrency) {
+ const options = { concurrency: true, isolation: 'process', execArgv: ['--disable-warning=ExperimentalWarning', '--import', runner] };
+ const reporters = [];
+ const selectors = [];
+ const patterns = [];
+ const skipPatterns = [];
+ const coverageExcludeGlobs = [];
+ const coverageIncludeGlobs = [];
+ const execArgv = [];
+ let expectValue = null;
+ for (let index = 0; index < args.length; index += 1) {
+ let argument = args[index];
+ if (expectValue) {
+ expectValue(argument);
+ expectValue = null;
+ continue;
+ }
+ if (argument === '--') { selectors.push(...args.slice(index + 1)); break; }
+ const valueOption = (name, take) => {
+ if (argument === name) { expectValue = take; return true; }
+ if (argument.startsWith(`${name}=`)) { take(argument.slice(name.length + 1)); return true; }
+ return false;
+ };
+ if (valueOption('--test-concurrency', value => {
+ if (value === 'true') options.concurrency = true;
+ else if (value === 'false') options.concurrency = false;
- else if (/^[1-9][0-9]*$/u.test(value)) options.concurrency = Number(value);
- else throw new Error(`invalid --test-concurrency value: ${value}`);
++ else if (/^[1-9][0-9]*$/u.test(value)) {
++ const requested = Number(value);
++ // Validate before clamping: Node's run() accepts a positive uint32, not Infinity or larger integers.
++ if (!Number.isSafeInteger(requested) || requested > 4_294_967_295) {
++ throw new Error(`invalid --test-concurrency value: ${value}`);
++ }
++ options.concurrency = requested;
++ } else throw new Error(`invalid --test-concurrency value: ${value}`);
+ })) continue;
+ if (valueOption('--test-name-pattern', value => patterns.push(value))) continue;
+ if (valueOption('--test-skip-pattern', value => skipPatterns.push(value))) continue;
+ if (valueOption('--test-timeout', value => { options.timeout = Number(value); })) continue;
+ if (valueOption('--test-reporter', value => reporters.push(value))) continue;
+ if (valueOption('--test-reporter-destination', value => { (options.reporterDestinations ??= []).push(value); })) continue;
+ if (valueOption('--test-coverage-include', value => coverageIncludeGlobs.push(value))) continue;
+ if (valueOption('--test-coverage-exclude', value => coverageExcludeGlobs.push(value))) continue;
+ if (valueOption('--test-coverage-lines', value => { options.lineCoverage = Number(value); })) continue;
+ if (valueOption('--test-coverage-branches', value => { options.branchCoverage = Number(value); })) continue;
+ if (valueOption('--test-coverage-functions', value => { options.functionCoverage = Number(value); })) continue;
+ if (argument === '--test-only') { options.only = true; continue; }
+ if (argument === '--experimental-test-coverage') { options.coverage = true; continue; }
+ if (argument.startsWith('--experimental-test-isolation=')) {
+ options.isolation = argument.slice(argument.indexOf('=') + 1);
+ continue;
+ }
+ if (argument.startsWith('--test-isolation=')) {
+ options.isolation = argument.slice(argument.indexOf('=') + 1);
+ continue;
+ }
+ if (argument === '--test-isolation') {
+ expectValue = value => { options.isolation = value; };
+ continue;
+ }
+ if (argument === '--experimental-test-isolation') {
+ expectValue = value => { options.isolation = value; };
+ continue;
+ }
+ if (argument === '--test-shard') { index += 1; continue; }
+ if (argument.startsWith('--test-shard=')) continue;
+ if (argument.startsWith('-')) {
+ execArgv.push(argument);
+ if (!argument.includes('=') && optionTakesValue(argument)) {
+ if (args[index + 1] === undefined) throw new Error(`${argument} requires a value`);
+ execArgv.push(args[++index]);
+ }
+ continue;
+ }
+ selectors.push(argument);
+ }
+ if (expectValue) throw new Error('missing value for a Node test runner option');
+ options.execArgv = [...options.execArgv, ...execArgv];
++ // Keep native run() from treating true/default or a larger explicit value as unbounded.
++ if (options.concurrency !== false) {
++ const requested = options.concurrency === true ? concurrency.files : options.concurrency;
++ options.concurrency = Math.min(concurrency.files, requested);
++ }
+ if (selectors.length) {
+ const { glob } = await import('node:fs/promises');
+ const files = [];
+ for (const selector of selectors) {
+ if (!/[?*[{]/u.test(selector)) {
+ files.push(resolve(selector));
+ continue;
+ }
+ const matches = [];
+ for await (const match of glob(selector, { cwd: process.cwd() })) matches.push(resolve(match));
+ if (!matches.length) throw new Error(`test file pattern matched no files: ${selector}`);
+ files.push(...matches.sort());
+ }
+ options.files = [...new Set(files)];
+ }
+ if (patterns.length) options.testNamePatterns = patterns;
+ if (skipPatterns.length) options.testSkipPatterns = skipPatterns;
+ if (coverageExcludeGlobs.length) options.coverageExcludeGlobs = coverageExcludeGlobs;
+ if (coverageIncludeGlobs.length) options.coverageIncludeGlobs = coverageIncludeGlobs;
+ if (args.includes('--test-shard') || args.some(argument => argument.startsWith('--test-shard='))) {
+ const shardArgument = args.find(argument => argument === '--test-shard' || argument.startsWith('--test-shard='));
+ const shard = shardArgument === '--test-shard' ? args[args.indexOf(shardArgument) + 1] : shardArgument.slice('--test-shard='.length);
+ const match = shard?.match(/^([1-9][0-9]*)\/([1-9][0-9]*)$/u);
+ if (!match) throw new Error(`invalid --test-shard value: ${shard ?? '(missing)'}`);
+ options.shard = { index: Number(match[1]), total: Number(match[2]) };
+ }
+ let selectedCandidates = options.files;
+ if (!selectedCandidates) {
+ const { glob } = await import('node:fs/promises');
+ const defaults = ['**/*.test.{cjs,mjs,js}', '**/*-test.{cjs,mjs,js}', '**/*_test.{cjs,mjs,js}',
+ '**/test-*.{cjs,mjs,js}', '**/test.{cjs,mjs,js}', '**/test/**/*.{cjs,mjs,js}'];
+ const matches = new Set();
+ for (const pattern of defaults) {
+ for await (const file of glob(pattern, { cwd: process.cwd() })) {
+ if (!file.split(/[\\/]/u).includes('node_modules')) matches.add(resolve(file));
+ }
+ }
+ selectedCandidates = [...matches].sort();
+ }
+ options.selectedFiles = selectedCandidates.filter((_file, index) => !options.shard || index % options.shard.total === options.shard.index - 1);
+ if (!reporters.length) reporters.push('tap');
+ const destinations = options.reporterDestinations ?? (reporters.length === 1 ? ['stdout'] : []);
+ if (destinations.length !== reporters.length) throw new Error('each --test-reporter requires a matching --test-reporter-destination');
+ options.reporters = reporters.map((reporter, index) => ({ reporter, destination: destinations[index] }));
+ delete options.reporterDestinations;
+ return { options, env };
+}
+
+/** Parse a POSIX process census into PID, group, and start identities used for safe cleanup. */
+function parseLandingProcessTable(output) {
+ const processes = [];
+ for (const line of output.split(/\r?\n/u)) {
+ const match = line.match(/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.+)$/u);
+ if (!match) continue;
+ const [, pidText, ppidText, pgidText, state, rest] = match;
+ const fields = rest.trim().split(/\s+/u);
+ if (fields.length < 5) continue;
+ const started = fields.slice(0, 5).join(' ');
+ const command = fields.slice(5).join(' ');
+ processes.push({ pid: Number(pidText), ppid: Number(ppidText), pgid: Number(pgidText), state, started, command, depth: 0 });
+ }
+ return processes;
+}
+
+/** Snapshot process identities on POSIX hosts, where the runner can verify process ancestry. */
+function landingProcessTable() {
+ if (process.platform === 'win32') return [];
+ const output = execFileSync('ps', ['-axo', 'pid=,ppid=,pgid=,stat=,lstart=,command='], { encoding: 'utf8', timeout: 2000 });
+ return parseLandingProcessTable(output);
+}
+
+/** Mark a worker identity retry interrupted by the runner's explicit SIGTERM cancellation. */
+function landingWorkerCancellationError(cause) {
+ const error = new Error('landing test worker identity retry was interrupted', cause ? { cause } : undefined);
+ error.code = 'LANDING_CANCELLED';
+ return error;
+}
+
+/** Retry a worker's initial process-identity receipt without blocking its event loop or exceeding the file-start ceiling. */
+async function landingWorkerIdentity(pid, timeoutMs = LANDING_WORKER_IDENTITY_TIMEOUT_MS) {
+ if (process.platform === 'win32') return null;
+ const deadline = Date.now() + timeoutMs;
+ let lastError = null;
+ let retryNoticeReported = false;
+ let stopping = false;
+ let snapshotChild = null;
+ const stopSnapshot = () => {
+ stopping = true;
+ snapshotChild?.kill('SIGTERM');
+ };
+ process.once('SIGTERM', stopSnapshot);
+ try {
+ while (Date.now() < deadline) {
+ if (stopping) throw landingWorkerCancellationError();
+ const remaining = deadline - Date.now();
+ if (remaining <= 0) break;
+ try {
+ const output = await new Promise((resolveOutput, rejectOutput) => {
+ const child = execFile('ps', ['-axo', 'pid=,ppid=,pgid=,stat=,lstart=,command='], {
+ encoding: 'utf8', timeout: Math.min(2000, Math.max(1, remaining)),
+ }, (error, stdout) => {
+ if (snapshotChild === child) snapshotChild = null;
+ error ? rejectOutput(error) : resolveOutput(stdout);
+ });
+ snapshotChild = child;
+ if (stopping) child.kill('SIGTERM');
+ });
+ if (stopping) throw landingWorkerCancellationError();
+ const identity = parseLandingProcessTable(output).find(processInfo => processInfo.pid === pid);
+ if (identity) {
+ if (stopping) throw landingWorkerCancellationError();
+ return identity;
+ }
+ } catch (error) {
+ if (stopping || error.code === 'LANDING_CANCELLED') throw landingWorkerCancellationError(error);
+ lastError = error;
+ if (!retryNoticeReported) {
+ retryNoticeReported = true;
+ const timedOut = error.code === 'ETIMEDOUT' || (error.killed === true && error.signal === 'SIGTERM'
+ && error.cmd === 'ps -axo pid=,ppid=,pgid=,stat=,lstart=,command=');
+ process.stderr.write(timedOut
+ ? 'run-tests: worker identity snapshot timed out; retrying before file execution\n'
+ : `run-tests: worker identity snapshot failed (${error.code ?? 'unknown'}); retrying before file execution\n`);
+ }
+ }
+ const wait = Math.min(100, deadline - Date.now());
+ if (wait > 0) await new Promise(resolveReady => setTimeout(resolveReady, wait));
+ }
+ if (stopping) throw landingWorkerCancellationError();
+ const unavailable = new Error(`landing test worker identity was unavailable within ${timeoutMs}ms`, { cause: lastError });
+ unavailable.code = 'LANDING_IDENTITY_UNAVAILABLE';
+ throw unavailable;
+ } finally {
+ process.off('SIGTERM', stopSnapshot);
+ snapshotChild = null;
+ }
+}
+
+/** Snapshot descendants only from worker identities still matching their startup receipts. */
+function landingWorkerDescendants(workerRoots, processes = landingProcessTable()) {
+ if (!workerRoots.length || process.platform === 'win32') return [];
+ const byParent = new Map();
+ const byPid = new Map(processes.map(processInfo => [processInfo.pid, processInfo]));
+ for (const child of processes) {
+ const children = byParent.get(child.ppid) ?? [];
+ children.push(child);
+ byParent.set(child.ppid, children);
+ }
+ const found = [];
+ const validRoots = workerRoots.filter(root => sameProcessIdentity(byPid.get(root.pid), root));
+ const visited = new Set(validRoots.map(root => root.pid));
+ const queue = validRoots.map(root => ({ pid: root.pid, depth: 0 }));
+ while (queue.length) {
+ const parent = queue.shift();
+ for (const child of byParent.get(parent.pid) ?? []) {
+ if (visited.has(child.pid)) continue;
+ visited.add(child.pid);
+ child.depth = parent.depth + 1;
+ found.push(child);
+ queue.push({ pid: child.pid, depth: child.depth });
+ }
+ }
+ return found;
+}
+
+/** Confirm a direct child is the announced Node worker for exactly one selected test file. */
+function landingWorkerCommandMatchesFile(processInfo, file) {
+ const command = processInfo.command.trimEnd();
+ const executable = command.match(/^(?:"([^"]+)"|'([^']+)'|(\S+))/u);
+ if (!executable) return false;
+ const executablePath = executable[1] ?? executable[2] ?? executable[3];
+ if (basename(executablePath) !== basename(process.execPath)) return false;
+ let offset = command.indexOf(file);
+ while (offset !== -1) {
+ const before = offset === 0 || /[\s"']/u.test(command[offset - 1]);
+ const afterIndex = offset + file.length;
+ const after = afterIndex === command.length || /[\s"']/u.test(command[afterIndex]);
+ if (before && after) return true;
+ offset = command.indexOf(file, offset + 1);
+ }
+ return false;
+}
+
+/** Match an announced ChildProcess spawn to the fresh command line without trusting its PID alone. */
+function landingChildCommandMatchesSpawn(processInfo, receipt) {
+ const command = processInfo.command.trimEnd();
+ const executable = command.match(/^(?:"([^"]+)"|'([^']+)'|(\S+))/u);
+ if (!executable || basename(executable[1] ?? executable[2] ?? executable[3]) !== basename(receipt.spawnFile ?? '')) return false;
+ return receipt.spawnArgs.slice(1).every(argument => {
+ if (typeof argument !== 'string' || !argument) return false;
+ let offset = command.indexOf(argument);
+ while (offset !== -1) {
+ const before = offset === 0 || /[\s"']/u.test(command[offset - 1]);
+ const afterIndex = offset + argument.length;
+ const after = afterIndex === command.length || /[\s"']/u.test(command[afterIndex]);
+ if (before && after) return true;
+ offset = command.indexOf(argument, offset + 1);
+ }
+ return false;
+ });
+}
+
+/** Keep the established healthy-worker path: snapshot only detached children at spawn time. */
+function watchLandingChildSpawns(startsPath, attempt) {
+ let recording = false;
+ channel('child_process').subscribe(({ process: child }) => {
+ if (recording || !child || typeof child.once !== 'function') return;
+ child.once('spawn', () => {
+ if (!Number.isInteger(child.pid)) return;
+ recording = true;
+ try {
+ const byPid = new Map(landingProcessTable().map(processInfo => [processInfo.pid, processInfo]));
+ const parent = byPid.get(process.pid);
+ const spawned = byPid.get(child.pid);
+ if (parent && spawned && spawned.pgid !== parent.pgid) {
+ appendFileSync(startsPath, `${JSON.stringify({ type: 'child', attempt, parentPid: process.pid,
+ pid: spawned.pid, pgid: spawned.pgid, started: spawned.started })}\n`);
+ }
+ } catch { /* The ancestry monitor remains the fallback if a receipt cannot be written. */ }
+ finally { recording = false; }
+ });
+ });
+}
+
+/** Publish child announcements without inspection, then retain degraded-worker custody until the parent responds. */
+function watchLandingChildCustody(startsPath, attempt) {
+ let sequence = 0;
+ const pending = new Map();
+ let poll = null;
+ let announcementFailureDeadline = null;
+ let announcedUnavailable = false;
+ let announcementFailureReportedToParent = false;
+ const directory = dirname(startsPath);
+ const prefix = `${basename(startsPath)}.child.${attempt}.${process.pid}.`;
+ const pollAcks = () => {
+ if (!pending.size && announcementFailureDeadline === null) return;
+ try {
+ for (const name of readdirSync(directory)) {
+ if (!name.startsWith(prefix) || !name.endsWith('.json')) continue;
+ const recordPath = join(directory, name);
+ if (!existsSync(`${recordPath}.ack`)) continue;
+ const record = JSON.parse(readFileSync(recordPath, 'utf8'));
+ const ack = JSON.parse(readFileSync(`${recordPath}.ack`, 'utf8'));
+ if (record.attempt !== attempt || record.parentPid !== process.pid
+ || ack.attempt !== attempt || ack.parentPid !== process.pid || ack.pid !== record.pid
+ || !['bound', 'drained', 'unverified'].includes(ack.status)) continue;
+ pending.delete(recordPath);
+ renameSync(`${recordPath}.ack`, `${recordPath}.acked`);
+ }
+ } catch { /* An unreadable acknowledgement retains worker custody. */ }
+ const now = Date.now();
+ const expired = [...pending].filter(([, deadline]) => now >= deadline).map(([path]) => path);
+ if (expired.length) {
+ for (const recordPath of expired) {
+ pending.delete(recordPath);
+ try {
+ const marker = `${recordPath}.expired`;
+ if (!existsSync(marker)) writeFileSync(marker, JSON.stringify({ attempt, parentPid: process.pid,
+ expiredAt: new Date(now).toISOString() }), { mode: 0o600, flag: 'wx' });
+ } catch { /* Parent-side cleanup reports uncertainty from the original child receipt. */ }
+ }
+ }
+ if (announcementFailureDeadline !== null && now >= announcementFailureDeadline && !announcedUnavailable) {
+ announcedUnavailable = true;
+ if (!announcementFailureReportedToParent) {
+ process.stderr.write('run-tests: cleanup for selected test file UNVERIFIED: child ownership announcement failed; no unverified process was signaled\n');
+ }
+ }
+ if (!pending.size && (announcementFailureDeadline === null || announcedUnavailable) && poll) { clearInterval(poll); poll = null; }
+ };
+ channel('child_process').subscribe(({ process: child }) => {
+ if (!child || typeof child.once !== 'function') return;
+ child.once('spawn', () => {
+ if (!Number.isInteger(child.pid)) return;
+ const recordPath = join(directory, `${prefix}${sequence++}.${randomUUID()}.json`);
+ const record = { type: 'child-pending', attempt, file: process.env.PULLBOARD_TEST_FILE,
+ parentPid: process.pid, pid: child.pid, spawnFile: child.spawnfile,
+ spawnArgs: Array.isArray(child.spawnargs) ? child.spawnargs : [] };
+ try {
+ const temporary = `${recordPath}.tmp`;
+ writeFileSync(temporary, JSON.stringify(record), { mode: 0o600, flag: 'wx' });
+ renameSync(temporary, recordPath);
+ pending.set(recordPath, Date.now() + LANDING_CHILD_CUSTODY_TIMEOUT_MS);
+ if (!poll) poll = setInterval(pollAcks, 25);
+ } catch (error) {
+ announcementFailureDeadline ??= Date.now() + LANDING_CHILD_CUSTODY_TIMEOUT_MS;
+ const code = String(error?.code ?? 'announcement-error').replace(/[\u0000-\u001f\u007f]/gu, ' ').slice(0, 80);
+ const reason = String(error?.message ?? error).replace(/[\u0000-\u001f\u007f]/gu, ' ').slice(0, 256);
+ let failurePublished = false;
+ try {
+ const failed = `${recordPath}.failure.json`;
+ const temporary = `${failed}.${randomUUID()}.tmp`;
+ writeFileSync(temporary, JSON.stringify({ type: 'child-announcement-failed', attempt,
+ file: record.file, parentPid: process.pid, pid: child.pid, code, reason }), { mode: 0o600, flag: 'wx' });
+ renameSync(temporary, failed);
+ failurePublished = true;
+ } catch { /* The worker still releases on its bounded timer; no process is signaled by guess. */ }
+ try {
+ appendFileSync(startsPath, `${JSON.stringify({ type: 'child-announcement-unavailable', attempt,
+ file: record.file, parentPid: process.pid, pid: child.pid, code, reason })}\n`);
+ failurePublished = true;
+ } catch { /* Worker stderr is the last bounded diagnostic fallback. */ }
+ announcementFailureReportedToParent ||= failurePublished;
+ if (!poll) poll = setInterval(pollAcks, 25);
+ }
+ });
+ });
+}
+
+/** Match a PID to its captured identity so cleanup never signals a reused PID. */
+function sameProcessIdentity(candidate, captured) {
+ return candidate && candidate.pid === captured.pid && candidate.pgid === captured.pgid && candidate.started === captured.started;
+}
+
+/** Publish an acknowledgement only after the parent has bound a child identity or observed a previously bound exit. */
+function writeChildAcknowledgement(recordPath, receipt, identity, status) {
+ const acknowledgement = `${recordPath}.ack`;
+ if (existsSync(acknowledgement) || existsSync(`${recordPath}.acked`)) return;
+ const temporary = `${acknowledgement}.${randomUUID()}.tmp`;
+ writeFileSync(temporary, JSON.stringify({ attempt: receipt.attempt, parentPid: receipt.parentPid,
+ pid: receipt.pid, status, identity }), { mode: 0o600, flag: 'wx' });
+ try { renameSync(temporary, acknowledgement); }
+ catch (error) { rmSync(temporary, { force: true }); if (error.code !== 'EEXIST') throw error; }
+}
+
+/** Read only complete append-only worker journal rows while workers may be writing. */
+function landingWorkerReceipts(path) {
+ const contents = readFileSync(path, 'utf8');
+ const complete = contents.endsWith('\n') ? contents : contents.slice(0, contents.lastIndexOf('\n') + 1);
+ return complete.split(/\r?\n/u).filter(Boolean).map(line => JSON.parse(line));
+}
+
+/** Terminate owned descendants as the live receipt set grows, then wait for the run and every identity to drain. */
+async function drainLandingWorkerDescendants(ownedDescendants, refreshOwnedDescendants, runFinished, reportUnverified, cleanupDeadline) {
+ let firstError = null;
+ let snapshotFailureSince = null;
+ let lastSnapshotError = null;
+ const rememberError = error => {
+ firstError ??= error;
+ if (firstError === error) {
+ process.stderr.write(`run-tests: descendant cleanup encountered ${error.message}; retaining the gate slot until captured processes drain\n`);
+ }
+ };
+ const rememberSnapshotError = error => {
+ snapshotFailureSince ??= Date.now();
+ lastSnapshotError = error;
+ };
+ const snapshot = () => {
+ try { return new Map(landingProcessTable().map(processInfo => [processInfo.pid, processInfo])); }
+ catch (error) { rememberSnapshotError(error); return null; }
+ };
+ const signalDue = captured => {
+ const current = snapshot();
+ if (!current) return;
+ const now = Date.now();
+ for (const owned of captured) {
+ const live = current.get(owned.pid);
+ if (!sameProcessIdentity(live, owned) || live.state.startsWith('Z')) continue;
+ const key = `${owned.pid}:${owned.pgid}:${owned.started}`;
+ const state = signalState.get(key) ?? { termAt: null, killSent: false };
+ const signal = state.termAt === null ? 'SIGTERM' : now - state.termAt >= 750 && !state.killSent ? 'SIGKILL' : null;
+ if (!signal) continue;
+ try {
+ process.kill(owned.pid, signal);
+ if (signal === 'SIGTERM') state.termAt = now;
+ else state.killSent = true;
+ } catch (error) {
+ if (error.code === 'ESRCH') continue;
+ rememberError(error);
+ }
+ signalState.set(key, state);
+ }
+ };
+ const remaining = () => {
+ const current = snapshot();
+ if (!current) return null;
+ return [...ownedDescendants.values()].filter(owned => {
+ const live = current.get(owned.pid);
+ return sameProcessIdentity(live, owned) && !live.state.startsWith('Z');
+ });
+ };
+ const signalState = new Map();
+ let nextSignal = 0;
+ let runFinishedWithoutOwnedProcesses = false;
+ let unresolvedSince = null;
+ while (true) {
+ let captureSucceeded = false;
+ try {
+ captureSucceeded = refreshOwnedDescendants() !== false;
+ } catch (error) { rememberSnapshotError(error); }
+ if (captureSucceeded) unresolvedSince = null;
+ else unresolvedSince ??= Date.now();
+ const stillOwned = remaining();
+ if (captureSucceeded && stillOwned) { snapshotFailureSince = null; lastSnapshotError = null; }
+ if ((snapshotFailureSince || unresolvedSince) && Date.now() >= cleanupDeadline) {
+ reportUnverified(lastSnapshotError);
+ break;
+ }
+ if (runFinished() && captureSucceeded && stillOwned && stillOwned.length === 0) {
+ if (runFinishedWithoutOwnedProcesses) break;
+ runFinishedWithoutOwnedProcesses = true;
+ } else {
+ runFinishedWithoutOwnedProcesses = false;
+ }
+ if (Date.now() >= nextSignal) {
+ signalDue([...ownedDescendants.values()]);
+ nextSignal = Date.now() + 100;
+ }
+ await new Promise(resolveReady => setTimeout(resolveReady, 100));
+ }
+ if (firstError) throw new Error(`owned descendants drained after cleanup error: ${firstError.message}`, { cause: firstError });
+}
+
+/** Run a landing check with execution-ordered failure detection and native runner reporters. */
- async function runLandingTests(args, env) {
++async function runLandingTests(args, env, concurrency) {
+ const { run } = await import('node:test');
+ const { PassThrough } = await import('node:stream');
+ const { createWriteStream } = await import('node:fs');
+ const { pathToFileURL } = await import('node:url');
- const { options, env: testEnv } = await landingTestOptions(args, env);
++ const { options, env: testEnv } = await landingTestOptions(args, env, concurrency);
+ if (options.isolation !== 'process') {
+ throw new Error('landing gate early-stop requires --test-isolation=process so started files and owned children can be tracked safely');
+ }
+ if (process.platform === 'win32') {
+ throw new Error('landing gate early-stop requires POSIX process identities to track and drain started files safely');
+ }
+ const attempt = randomUUID();
+ const workerStartsPath = join(testEnv.TMPDIR ?? tmpdir(), `landing-worker-starts-${attempt}.jsonl`);
+ writeFileSync(workerStartsPath, '', { mode: 0o600 });
+ testEnv[LANDING_WORKER_STARTS_ENV] = workerStartsPath;
+ testEnv[LANDING_ATTEMPT_ENV] = attempt;
+ watchLandingChildSpawns(workerStartsPath, attempt);
+ const selectedFiles = options.selectedFiles;
+ delete options.selectedFiles;
+ const reporterEntries = options.reporters;
+ delete options.reporters;
+ const loadedReporters = [];
+ for (const entry of reporterEntries) {
+ let reporter;
+ if (['tap', 'spec', 'dot', 'junit', 'lcov'].includes(entry.reporter)) {
+ reporter = (await import('node:test/reporters'))[entry.reporter];
+ } else {
+ const moduleSpecifier = entry.reporter.startsWith('.') || entry.reporter.startsWith('/')
+ ? pathToFileURL(resolve(entry.reporter)).href : entry.reporter;
+ const imported = await import(moduleSpecifier);
+ reporter = imported.default;
+ }
+ if (!reporter) throw new Error(`unknown test reporter: ${entry.reporter}`);
+ loadedReporters.push(reporter);
+ }
+ const reporters = [];
+ const reporterEnds = [];
+ const controller = new AbortController();
+ let reporterError = null;
+ for (const [index, entry] of reporterEntries.entries()) {
+ const reporter = loadedReporters[index];
+ const input = new PassThrough({ objectMode: true });
+ const output = input.compose(reporter);
+ const destination = entry.destination === 'stdout' ? process.stdout
+ : entry.destination === 'stderr' ? process.stderr : createWriteStream(resolve(entry.destination));
+ const readableEnd = new Promise(resolveEnd => {
+ output.once('end', resolveEnd);
+ output.once('close', resolveEnd);
+ });
+ const handleReporterError = error => { reporterError ??= error; abortLandingRun(); };
+ if (entry.destination === 'stdout' || entry.destination === 'stderr') {
+ output.once('error', handleReporterError);
+ destination.once('error', handleReporterError);
+ output.pipe(destination);
+ reporterEnds.push(readableEnd.finally(() => destination.off('error', handleReporterError)));
+ } else {
+ const writableEnd = new Promise((resolveEnd, reject) => {
+ destination.once('finish', resolveEnd);
+ destination.once('error', error => { handleReporterError(error); reject(error); });
+ output.once('error', error => { handleReporterError(error); reject(error); });
+ });
+ output.pipe(destination);
+ reporterEnds.push(Promise.all([readableEnd, writableEnd]).catch(error => { reporterError = error; abortLandingRun(); }));
+ }
+ reporters.push(input);
+ }
+ const startedFiles = new Set();
+ const completedFiles = new Set();
+ const failureDiagnostics = new Map();
+ let firstFailure = null;
+ let successful = true;
+ let reportersEnded = false;
+ let abortCleaned = false;
+ let abortPromise = null;
+ let cleanupDeadline = null;
+ let workerDrain = Promise.resolve();
+ let runFinished = false;
+ const ownedDescendants = new Map();
+ const pendingWorkerBindings = new Map();
+ const pendingChildBindings = new Map();
+ const unverifiedChildBindings = new Set();
+ const acknowledgedChildDrains = new Set();
+ const selectedFileSet = new Set(selectedFiles ?? []);
+ let cleanupUnverifiedReported = false;
+ let lastCleanupSnapshotError = null;
+ const cleanupUnverifiedFiles = new Set();
+ const reportCleanupUnverified = error => {
+ if (cleanupUnverifiedReported) return;
+ cleanupUnverifiedReported = true;
+ const files = [...cleanupUnverifiedFiles].map(file => basename(file));
+ const fallbackFiles = [...selectedFileSet].map(file => basename(file));
+ const namedFiles = files.length ? files : fallbackFiles;
+ const shownFiles = namedFiles.slice(0, 12);
+ const subject = shownFiles.length ? `${shownFiles.join(', ')}${namedFiles.length > shownFiles.length ? ` (+${namedFiles.length - shownFiles.length} more)` : ''}` : 'selected test files';
+ const code = String(error?.code ?? 'snapshot-unavailable')
+ .replace(/[\u0000-\u001f\u007f]/gu, ' ').slice(0, 80);
+ const detail = String(error?.message ?? 'process identity census unavailable')
+ .replace(/[\u0000-\u001f\u007f]/gu, ' ').slice(0, 256);
+ const reason = detail === code ? code : `${code}: ${detail}`;
+ process.stderr.write(`run-tests: cleanup for ${subject} UNVERIFIED: ${reason}; no unverified process was signaled\n`);
+ };
+ const rememberSnapshotError = error => {
+ lastCleanupSnapshotError = error;
+ };
+ const captureOwnedDescendants = () => {
+ const processes = landingProcessTable();
+ const receipts = landingWorkerReceipts(workerStartsPath).filter(receipt => receipt.attempt === attempt);
+ const current = new Map(processes.map(processInfo => [processInfo.pid, processInfo]));
+ const workerRoots = receipts.filter(receipt => receipt.type === 'worker' && selectedFileSet.has(receipt.file)
+ && sameProcessIdentity(current.get(receipt.pid), receipt));
+ for (const receipt of receipts) {
+ if (receipt.type !== 'worker-pending' || !selectedFileSet.has(receipt.file)
+ || receipt.parentPid !== process.pid || !Number.isInteger(receipt.pid)) continue;
+ const key = `${receipt.attempt}:${receipt.pid}:${receipt.file}`;
+ const previouslyBound = pendingWorkerBindings.get(key);
+ if (previouslyBound) {
+ if (sameProcessIdentity(current.get(previouslyBound.pid), previouslyBound)) workerRoots.push(previouslyBound);
+ continue;
+ }
+ const candidate = current.get(receipt.pid);
+ if (!candidate || candidate.ppid !== process.pid || candidate.state.startsWith('Z')
+ || !Number.isInteger(candidate.pgid) || !candidate.started
+ || !landingWorkerCommandMatchesFile(candidate, receipt.file)) continue;
+ // Bind an announcement once. A later process reusing this PID can never replace it.
+ pendingWorkerBindings.set(key, candidate);
+ workerRoots.push(candidate);
+ appendFileSync(workerStartsPath, `${JSON.stringify({ type: 'worker-bound', attempt, file: receipt.file,
+ pid: candidate.pid, parentPid: process.pid, pgid: candidate.pgid, started: candidate.started })}\n`);
+ }
+ const workerByPid = new Map(workerRoots.map(root => [root.pid, root]));
+ let unsettledChild = false;
+ for (const receipt of receipts) {
+ if (receipt.type !== 'child-announcement-unavailable' || !selectedFileSet.has(receipt.file)) continue;
+ unsettledChild = true;
+ cleanupUnverifiedFiles.add(receipt.file);
+ lastCleanupSnapshotError = { code: receipt.code, message: receipt.reason };
+ }
+ for (const name of readdirSync(dirname(workerStartsPath))) {
+ const prefix = `${basename(workerStartsPath)}.child.${attempt}.`;
+ if (!name.startsWith(prefix) || !name.endsWith('.json')) continue;
+ const recordPath = join(dirname(workerStartsPath), name);
+ let receipt;
+ try { receipt = JSON.parse(readFileSync(recordPath, 'utf8')); }
+ catch { continue; }
+ if (receipt.type === 'child-announcement-failed' && receipt.attempt === attempt
+ && selectedFileSet.has(receipt.file)) {
+ unsettledChild = true;
+ cleanupUnverifiedFiles.add(receipt.file);
+ lastCleanupSnapshotError = { code: receipt.code, message: receipt.reason };
+ continue;
+ }
+ if (receipt.type !== 'child-pending' || receipt.attempt !== attempt || !selectedFileSet.has(receipt.file)
+ || !Number.isInteger(receipt.parentPid) || !Number.isInteger(receipt.pid)) continue;
+ const key = `${receipt.attempt}:${receipt.parentPid}:${receipt.pid}:${name}`;
+ if (unverifiedChildBindings.has(key)) continue;
+ const prior = pendingChildBindings.get(key);
+ if (prior) {
+ const live = current.get(prior.pid);
+ if (sameProcessIdentity(live, prior)) ownedDescendants.set(`${prior.pid}:${prior.pgid}:${prior.started}`, prior);
+ else if (!live || live.state.startsWith('Z')) {
+ if (!acknowledgedChildDrains.has(key)) {
+ writeChildAcknowledgement(recordPath, receipt, prior, 'drained');
+ acknowledgedChildDrains.add(key);
+ }
+ }
+ else unsettledChild = true;
+ continue;
+ }
+ const worker = workerByPid.get(receipt.parentPid);
+ const candidate = current.get(receipt.pid);
+ if (!worker || !candidate || candidate.ppid !== worker.pid || candidate.state.startsWith('Z')
+ || !Number.isInteger(candidate.pgid) || !candidate.started
+ || !landingChildCommandMatchesSpawn(candidate, receipt)) { unsettledChild = true; cleanupUnverifiedFiles.add(receipt.file); continue; }
+ // Capture ownership before acknowledging. The worker cannot exit/reparent this child first.
+ pendingChildBindings.set(key, candidate);
+ ownedDescendants.set(`${candidate.pid}:${candidate.pgid}:${candidate.started}`, candidate);
+ writeChildAcknowledgement(recordPath, receipt, candidate, 'bound');
+ }
+ const childRoots = receipts.filter(receipt => receipt.type === 'child' && sameProcessIdentity(current.get(receipt.pid), receipt));
+ const knownRoots = [...ownedDescendants.values()].filter(root => sameProcessIdentity(current.get(root.pid), root));
+ for (const root of childRoots) ownedDescendants.set(`${root.pid}:${root.pgid}:${root.started}`, current.get(root.pid));
+ for (const child of landingWorkerDescendants([...workerRoots, ...childRoots, ...knownRoots], processes)) {
+ ownedDescendants.set(`${child.pid}:${child.pgid}:${child.started}`, child);
+ }
+ return !unsettledChild;
+ };
+ const markPendingChildrenUnverified = () => {
+ const prefix = `${basename(workerStartsPath)}.child.${attempt}.`;
+ for (const name of readdirSync(dirname(workerStartsPath))) {
+ if (!name.startsWith(prefix) || !name.endsWith('.json')) continue;
+ const recordPath = join(dirname(workerStartsPath), name);
+ let receipt;
+ try { receipt = JSON.parse(readFileSync(recordPath, 'utf8')); }
+ catch { continue; }
+ if (receipt.type === 'child-announcement-failed' && receipt.attempt === attempt
+ && selectedFileSet.has(receipt.file)) {
+ cleanupUnverifiedFiles.add(receipt.file);
+ lastCleanupSnapshotError = { code: receipt.code, message: receipt.reason };
+ continue;
+ }
+ if (receipt.type !== 'child-pending' || receipt.attempt !== attempt || !selectedFileSet.has(receipt.file)) continue;
+ const key = `${receipt.attempt}:${receipt.parentPid}:${receipt.pid}:${name}`;
+ if (pendingChildBindings.has(key)) continue;
+ cleanupUnverifiedFiles.add(receipt.file);
+ if (!existsSync(`${recordPath}.expired`)) writeChildAcknowledgement(recordPath, receipt, null, 'unverified');
+ unverifiedChildBindings.add(key);
+ }
+ };
+ // Capture identities while worker ancestry still exists; a detached child can be
+ // reparented before the failure event reaches this process.
+ const descendantMonitor = setInterval(() => {
+ try { captureOwnedDescendants(); }
+ catch (error) { rememberSnapshotError(error); }
+ }, 1000);
+ descendantMonitor.unref();
+ const endReporters = () => {
+ if (reportersEnded) return;
+ reportersEnded = true;
+ for (const reporter of reporters) reporter.end();
+ };
+ const abortLandingRun = () => {
+ if (abortPromise) return abortPromise;
+ abortCleaned = true;
+ cleanupDeadline = Date.now() + LANDING_CHILD_CUSTODY_TIMEOUT_MS;
+ let resolveAbort;
+ abortPromise = new Promise(resolve => { resolveAbort = resolve; });
+ void (async () => {
+ try {
+ const captured = captureOwnedDescendants();
+ if (!captured) {
+ markPendingChildrenUnverified();
+ reportCleanupUnverified(lastCleanupSnapshotError);
+ }
+ } catch (error) {
+ rememberSnapshotError(error);
+ markPendingChildrenUnverified();
+ reportCleanupUnverified(lastCleanupSnapshotError);
+ } finally {
+ controller.abort();
+ }
+ })().then(resolveAbort, error => { reporterError ??= error; resolveAbort(); });
+ return abortPromise;
+ };
+ const originalEnv = { ...process.env };
+ for (const key of Object.keys(process.env)) delete process.env[key];
+ Object.assign(process.env, testEnv, { [LANDING_RUN_ENV]: '0' });
+ try {
+ const stream = run({ ...options, signal: controller.signal,
+ setup(tests) {
+ tests.on('test:complete', data => {
+ const { file, name, details } = data;
+ if (file && details?.type === 'test' && details.passed === false && !firstFailure) {
+ firstFailure = { file, name, error: details.error };
+ abortLandingRun();
+ }
+ });
+ tests.on('test:summary', data => {
+ if (data.success === false) successful = false;
+ if (data.file) {
+ startedFiles.add(data.file);
+ completedFiles.add(data.file);
+ if (data.success === false && !firstFailure) {
+ firstFailure = { file: data.file, name: 'test file failed before a test completed' };
+ abortLandingRun();
+ }
+ }
+ });
+ },
+ });
+ stream.on('data', event => {
+ // Node 22's execution-complete event may describe only the failed file wrapper;
+ // its ordered failure event retains the actual assertion once reporters drain.
+ if (event.type === 'test:fail') {
+ const data = event.data;
+ const error = data.details?.error;
+ if (data.file && error && !['testAborted', 'subtestsFailed'].includes(error.failureType)
+ && !failureDiagnostics.has(data.file)) failureDiagnostics.set(data.file, data);
+ }
+ for (const reporter of reporters) reporter.write(event);
+ });
+ stream.on('end', endReporters);
+ let streamClosed = false;
+ let resolveClosed;
+ const closed = new Promise(resolveDone => { resolveClosed = resolveDone; });
+ stream.once('close', () => { streamClosed = true; resolveClosed(); });
+ let streamErrored = false;
+ await new Promise(resolveDone => {
+ const finish = () => resolveDone();
+ stream.once('end', finish);
+ stream.once('close', finish);
+ stream.once('error', error => {
+ streamErrored = true;
+ reporterError ??= error;
+ abortLandingRun();
+ endReporters();
+ finish();
+ });
+ });
+ if (streamErrored && !streamClosed) await closed;
+ await abortPromise;
+ await Promise.all(reporterEnds);
+ runFinished = true;
+ for (const receipt of landingWorkerReceipts(workerStartsPath)) {
+ if (receipt.attempt === attempt && ['worker', 'worker-identity-unavailable'].includes(receipt.type)
+ && typeof receipt.file === 'string') startedFiles.add(receipt.file);
+ }
+ } finally {
+ if (!abortCleaned) await abortLandingRun();
+ else await abortPromise;
+ runFinished = true;
+ workerDrain = drainLandingWorkerDescendants(ownedDescendants, captureOwnedDescendants, () => runFinished,
+ reportCleanupUnverified, cleanupDeadline ?? Date.now() + LANDING_CHILD_CUSTODY_TIMEOUT_MS)
+ .catch(error => { reporterError ??= error; });
+ await workerDrain;
+ clearInterval(descendantMonitor);
+ endReporters();
+ for (const key of Object.keys(process.env)) delete process.env[key];
+ Object.assign(process.env, originalEnv);
+ }
+ if (reporterError) throw reporterError;
+ if (firstFailure) {
+ const diagnostic = failureDiagnostics.get(firstFailure.file);
+ if (diagnostic) firstFailure = { file: firstFailure.file, name: diagnostic.name, error: diagnostic.details.error };
+ const notRun = (selectedFiles ?? []).filter(file => !startedFiles.has(file));
+ const interrupted = [...startedFiles].filter(file => !completedFiles.has(file));
+ process.stderr.write(`\nLanding gate stopped early after ${firstFailure.file}: ${firstFailure.name}\n`);
+ if (firstFailure.error) {
+ const error = firstFailure.error;
+ const cause = error.cause?.message;
+ const message = [...new Set([error.message, cause].filter(Boolean))].join(': ')
+ .replace(/[\u0000-\u001f\u007f]/gu, ' ').slice(0, 4096);
+ if (message) process.stderr.write(`Triggering test error: ${message}\n`);
+ }
+ if (interrupted.length) process.stderr.write(`Interrupted test files: ${interrupted.join(', ')}\n`);
+ if (notRun.length) process.stderr.write(`Files not run: ${notRun.join(', ')}\n`);
+ process.exitCode = 1;
+ return { status: 1, signal: null };
+ }
+ return { status: successful ? 0 : 1, signal: null };
+}
+
let nodeOptionsWithValues;
/** Read Node option arity from this runtime so supported option values cannot bypass the machine pool. */
@@@ -1193,8 -369,12 +1221,12 @@@ function shardArguments(args)
}
/** Run tests in the disposable environment, preserving a marker only when a parent holds the slot. */
- async function executeTests(args, sandbox, gateMarkers, fullSuite) {
-function executeTests(args, sandbox, gateMarkers, fullSuite, concurrency) {
++async 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_BROWSER_OWNER_PID;
let selectedArgs = args;
if (fullSuite) {
let files;
@@@ -1215,9 -395,7 +1247,9 @@@
}
if (files) selectedArgs = [...args, ...files];
}
- const result = runTests(selectedArgs, env, concurrency);
+ const result = process.env[LANDING_RUN_ENV] === '1'
- ? await runLandingTests(selectedArgs, env)
- : runTests(selectedArgs, env);
++ ? await runLandingTests(selectedArgs, env, concurrency)
++ : runTests(selectedArgs, env, concurrency);
if (result.error) throw result.error;
return result;
}
@@@ -1251,10 -432,10 +1286,10 @@@ async function main(args)
}
let signal = null;
/** Keep sandbox lifetime inside the held lease, including the complete child process. */
- const run = (gateMarkers) => {
+ const run = async (gateMarkers) => {
const sandbox = mkdtempSync(join(tmpdir(), 'pullboard-test-run-'));
try {
- const result = await executeTests(args, sandbox, gateMarkers, fullSuite);
- const result = executeTests(args, sandbox, gateMarkers, fullSuite, concurrency);
++ const result = await executeTests(args, sandbox, gateMarkers, fullSuite, concurrency);
signal = result.signal;
process.exitCode = result.status ?? 1;
} finally { rmSync(sandbox, { recursive: true, force: true }); }
@@@ -1300,29 -481,17 +1335,45 @@@ if (process.argv[1] && resolve(process.
await main(process.argv.slice(2));
} else if (process.argv[1]) {
process.env.PULLBOARD_TEST_FILE = process.argv[1];
- installTestWatchdog();
- if (process.env.PULLBOARD_TEST_BROWSER_RESOURCE && process.env.NODE_TEST_CONTEXT === 'child-v8' && !process.env.PULLBOARD_TEST_BROWSER_OWNER_PID) {
- // Each native worker inherits an empty owner; its own forks inherit this PID and must not queue behind it.
+ const startsPath = process.env[LANDING_WORKER_STARTS_ENV];
+ const attempt = process.env[LANDING_ATTEMPT_ENV];
- if (startsPath && attempt) {
++ const landingWorker = Boolean(startsPath && attempt);
++ if (landingWorker) {
++ // Preserve #589 timing/custody behavior and announce before any browser-capacity wait.
++ installTestWatchdog();
+ const file = resolve(process.argv[1]);
+ let identityAvailable = false;
+ appendFileSync(startsPath, `${JSON.stringify({ type: 'worker-pending', attempt, file,
+ pid: process.pid, parentPid: process.ppid })}\n`);
+ try {
+ const identity = await landingWorkerIdentity(process.pid);
+ appendFileSync(startsPath, `${JSON.stringify({ type: 'worker', attempt, file,
+ pid: identity.pid, pgid: identity.pgid, started: identity.started })}\n`);
+ identityAvailable = true;
+ } catch (error) {
+ if (error.code === 'LANDING_CANCELLED') throw error;
+ const code = error.cause?.code ?? error.code ?? 'snapshot-error';
+ const reason = String(error.cause?.message ?? error.message ?? error)
+ .replace(/[\u0000-\u001f\u007f]/gu, ' ').slice(0, 512);
+ appendFileSync(startsPath, `${JSON.stringify({ type: 'worker-identity-unavailable', attempt, file,
+ pid: process.pid, parentPid: process.ppid, code, reason })}\n`);
+ process.stderr.write(`run-tests: worker identity unavailable (${code}): ${reason}\n`);
+ }
+ if (identityAvailable) watchLandingChildSpawns(startsPath, attempt);
+ else watchLandingChildCustody(startsPath, attempt);
+ }
++ if (process.env.PULLBOARD_TEST_BROWSER_RESOURCE && process.env.NODE_TEST_CONTEXT === 'child-v8'
++ && !process.env.PULLBOARD_TEST_BROWSER_OWNER_PID) {
++ // The worker is announced to #589 before it can wait here; admission remains before file import/body.
+ process.env.PULLBOARD_TEST_BROWSER_OWNER_PID = String(process.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.
++ // Hold through file cleanup and process exit, including abort/watchdog paths.
+ process.once('exit', () => lease.release());
+ }
+ }
- installTestWatchdog();
++ if (!landingWorker) installTestWatchdog();
}
diff --cc test/gate.test.js
index f3088bd0,c77cd76b..b7946574
--- a/test/gate.test.js
+++ b/test/gate.test.js
@@@ -18,6 -18,86 +18,111 @@@ 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',
++ const cases = [
++ { name: 'spawnSync explicit large integer', args: ['--test-concurrency=9'], landing: false },
++ { name: 'landing default', args: [], landing: true },
++ { name: 'landing true override', args: ['--test-concurrency=true'], landing: true },
++ { name: 'landing large integer override', args: ['--test-concurrency=9'], landing: true },
++ { name: 'landing serial override', args: ['--test-concurrency=false'], landing: true, serial: true },
++ ];
++ for (const [caseIndex, example] of cases.entries()) {
++ const capture = join(root, `overlap-${setting.files}-${caseIndex}.jsonl`);
++ const env = { ...process.env, PULLBOARD_CAP_CAPTURE: capture,
++ PULLBOARD_MACHINE_HOME: join(root, `machine-${setting.files}-${caseIndex}`) };
++ env.PULLBOARD_LANDING_RUN = example.landing ? '1' : '0';
++ const result = runFixtureChild(process.execPath, [join(root, 'bin/run-tests.js'), ...example.args, ...selected], {
++ cwd: root, env, encoding: 'utf8',
++ });
++ assert.equal(result.status, 0, `${example.name}: ${result.stdout}${result.stderr}`);
++ const peak = fileOverlap(capture);
++ assert.ok(peak.files <= setting.files, `${example.name}: file-body overlap ${peak.files} exceeds ${setting.files}`);
++ assert.ok(peak.browser <= setting.browser, `${example.name}: browser-file overlap ${peak.browser} exceeds ${setting.browser}`);
++ if (example.serial) assert.equal(peak.files, 1, 'false keeps the native runner serial');
++ assert.deepEqual(peak.starts.sort((a, b) => a - b), Array.from({ length: 9 }, (_, id) => id),
++ `${example.name}: every selected file runs once`);
++ assert.match(result.stdout, /# tests 9\b/u);
++ assert.match(result.stdout, /# fail 0\b/u);
++ }
++ }
++ writeFileSync(config, JSON.stringify({ testConcurrency: { files: 3, browser: 2 } }));
++ for (const value of ['4294967296', '9'.repeat(400)]) {
++ const capture = join(root, `invalid-concurrency-${value.length}.jsonl`);
++ const result = runFixtureChild(process.execPath, [join(root, 'bin/run-tests.js'),
++ `--test-concurrency=${value}`, ...selected], {
++ cwd: root, env: { ...process.env, PULLBOARD_LANDING_RUN: '1', PULLBOARD_CAP_CAPTURE: capture,
++ PULLBOARD_MACHINE_HOME: join(root, `machine-invalid-${value.length}`) }, 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/);
++ assert.notEqual(result.status, 0, 'an invalid native concurrency value is refused');
++ assert.match(result.stderr, /invalid --test-concurrency value/u);
++ assert.equal(existsSync(capture), false, 'invalid concurrency is refused before any file body runs');
+ }
+ let isolationCase = 0;
+ for (const flag of ['--test-isolation', '--test_isolation', '--experimental-test-isolation',
+ '--experimental_test_isolation', '--experimental_test-isolation', '--experimental-test_isolation']) {
+ for (const args of [[`${flag}=none`], [flag, 'none']]) {
+ const capture = join(root, `isolation-${isolationCase++}.jsonl`);
+ const result = runFixtureChild(process.execPath, [join(root, 'bin/run-tests.js'), ...args, selected.at(-1)], {
+ cwd: root, env: { ...process.env, PULLBOARD_CAP_CAPTURE: capture,
+ PULLBOARD_MACHINE_HOME: join(root, 'machine-isolation') }, encoding: 'utf8',
+ });
+ assert.notEqual(result.status, 0, `${args.join(' ')} must refuse non-isolated test files`);
+ assert.match(result.stderr, /bounded browser test files require process isolation/u);
+ assert.equal(existsSync(capture), false, 'a refused isolation mode never starts a test-file body');
+ }
+ }
+ 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.