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 landing test startup snapshots [C7,V4]

Corey Olson6c97d55b861a
diff --git a/bin/run-tests.js b/bin/run-tests.js
index 2166ff40..5709b322 100644
--- a/bin/run-tests.js
+++ b/bin/run-tests.js
@@ -2,18 +2,25 @@
/**
* Run the test suite with a private home, no inherited Git identity or config, and a refusing CLI shim.
*/
-import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { appendFileSync, chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { delimiter, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
-import { execFileSync, spawnSync } from 'node:child_process';
+import { execFile, execFileSync, spawnSync } from 'node:child_process';
import { tmpdir } from 'node:os';
import { after, afterEach, beforeEach } from 'node:test';
import { Worker } from 'node:worker_threads';
+import { randomUUID } from 'node:crypto';
+import { channel } from 'node:diagnostics_channel';
import { AGENT_SHELL_MARKERS, SSH_SHELL_MARKERS } from '../src/person.js';
const runner = fileURLToPath(import.meta.url);
+const LANDING_RUN_ENV = 'PULLBOARD_LANDING_RUN';
+const LANDING_WORKER_STARTS_ENV = 'PULLBOARD_LANDING_WORKER_STARTS';
+const LANDING_ATTEMPT_ENV = 'PULLBOARD_LANDING_ATTEMPT';
export const DEFAULT_TEST_TIMEOUT_MS = 660_000;
export const DEFAULT_TEST_FILE_TIMEOUT_MS = 30_000;
+// Worker identity startup retries stay below the ordinary per-file ceiling even if ps is unavailable.
+const LANDING_WORKER_IDENTITY_TIMEOUT_MS = 12_000;
const watchdogSource = `
const { parentPort } = require('node:worker_threads');
@@ -223,7 +230,13 @@ function testEnvironment(sandbox, gateMarkers = {}) {
delete env.PULLBOARD_RELAY_TOKEN; // Fixtures must supply their own scoped credentials, never an agent’s live bearer.
delete env.NODE_TEST_CONTEXT;
delete env.PULLBOARD_TEST_FILE;
+ delete env[LANDING_WORKER_STARTS_ENV];
+ delete env[LANDING_ATTEMPT_ENV];
+ // The outer gate decides whether this invocation is fail-fast. Its test workers and
+ // any nested runner commands always retain ordinary runner semantics.
+ env[LANDING_RUN_ENV] = '0';
Object.assign(env, gateMarkers);
+ env[LANDING_RUN_ENV] = '0';
return env;
}
@@ -247,6 +260,563 @@ function runTests(args, env) {
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) {
+ 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}`);
+ })) 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];
+ 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);
+}
+
+/** 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 stopping = false;
+ let snapshotChild = null;
+ const stopSnapshot = () => {
+ stopping = true;
+ snapshotChild?.kill('SIGTERM');
+ };
+ process.once('SIGTERM', stopSnapshot);
+ try {
+ while (Date.now() < deadline) {
+ if (stopping) throw new Error('landing test worker identity retry was interrupted');
+ 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');
+ });
+ const identity = parseLandingProcessTable(output).find(processInfo => processInfo.pid === pid);
+ if (identity) return identity;
+ } catch (error) {
+ if (stopping) throw new Error('landing test worker identity retry was interrupted', { cause: error });
+ const snapshotTimedOut = error.code === 'ETIMEDOUT' || (error.killed === true && error.signal === 'SIGTERM'
+ && error.cmd === 'ps -axo pid=,ppid=,pgid=,stat=,lstart=,command=');
+ if (!snapshotTimedOut) throw error;
+ lastError = error;
+ process.stderr.write('run-tests: worker identity snapshot timed out; retrying before file execution\n');
+ }
+ const wait = Math.min(100, deadline - Date.now());
+ if (wait > 0) await new Promise(resolveReady => setTimeout(resolveReady, wait));
+ }
+ throw new Error(`landing test worker identity was unavailable within ${timeoutMs}ms`, { cause: lastError });
+ } 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;
+}
+
+/** Journal detached child identities at spawn time, before a short-lived worker can exit. */
+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; }
+ });
+ });
+}
+
+/** 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;
+}
+
+/** 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) {
+ let firstError = null;
+ let snapshotTimeoutReported = false;
+ 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`);
+ }
+ };
+ // A missed observation proves neither a leak nor an empty process table. Retry it;
+ // only a later successful census can authorize signaling or release the lease.
+ const rememberSnapshotError = error => {
+ if (error.code !== 'ETIMEDOUT') { rememberError(error); return; }
+ if (!snapshotTimeoutReported) {
+ snapshotTimeoutReported = true;
+ process.stderr.write('run-tests: process snapshot timed out; retrying ownership census before gate-slot release\n');
+ }
+ };
+ 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;
+ while (true) {
+ let captureSucceeded = false;
+ try {
+ refreshOwnedDescendants();
+ captureSucceeded = true;
+ } catch (error) { rememberSnapshotError(error); }
+ const stillOwned = remaining();
+ 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) {
+ 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);
+ 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 workerDrain = Promise.resolve();
+ let runFinished = false;
+ const ownedDescendants = new Map();
+ let snapshotTimeoutReported = false;
+ const rememberSnapshotError = error => {
+ if (error.code !== 'ETIMEDOUT') { reporterError ??= error; return; }
+ if (!snapshotTimeoutReported) {
+ snapshotTimeoutReported = true;
+ process.stderr.write('run-tests: process snapshot timed out; awaiting a successful ownership census\n');
+ }
+ };
+ const captureOwnedDescendants = () => {
+ const processes = landingProcessTable();
+ const receipts = landingWorkerReceipts(workerStartsPath).filter(receipt => receipt.attempt === attempt);
+ const workerRoots = receipts.filter(receipt => receipt.type === 'worker' && sameProcessIdentity(
+ processes.find(processInfo => processInfo.pid === receipt.pid), receipt));
+ const current = new Map(processes.map(processInfo => [processInfo.pid, processInfo]));
+ 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);
+ }
+ };
+ // 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;
+ let resolveAbort;
+ abortPromise = new Promise(resolve => { resolveAbort = resolve; });
+ void (async () => {
+ // A failed process-table snapshot cannot authorize signals or lease release. Retry until
+ // ownership is known, then drain while the file workers still have their identities.
+ while (true) {
+ try { captureOwnedDescendants(); break; }
+ catch (error) {
+ rememberSnapshotError(error);
+ await new Promise(resolveReady => setTimeout(resolveReady, 100));
+ }
+ }
+ 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 && receipt.type === 'worker' && typeof receipt.file === 'string') startedFiles.add(receipt.file);
+ }
+ } finally {
+ if (!abortCleaned) await abortLandingRun();
+ else await abortPromise;
+ runFinished = true;
+ workerDrain = drainLandingWorkerDescendants(ownedDescendants, captureOwnedDescendants, () => runFinished)
+ .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. */
@@ -375,7 +945,7 @@ 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) {
+async function executeTests(args, sandbox, gateMarkers, fullSuite) {
const env = testEnvironment(sandbox, gateMarkers);
let selectedArgs = args;
if (fullSuite) {
@@ -397,7 +967,9 @@ function executeTests(args, sandbox, gateMarkers, fullSuite) {
}
if (files) selectedArgs = [...args, ...files];
}
- const result = runTests(selectedArgs, env);
+ const result = process.env[LANDING_RUN_ENV] === '1'
+ ? await runLandingTests(selectedArgs, env)
+ : runTests(selectedArgs, env);
if (result.error) throw result.error;
return result;
}
@@ -431,10 +1003,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 = executeTests(args, sandbox, gateMarkers, fullSuite);
+ const result = await executeTests(args, sandbox, gateMarkers, fullSuite);
signal = result.signal;
process.exitCode = result.status ?? 1;
} finally { rmSync(sandbox, { recursive: true, force: true }); }
@@ -445,7 +1017,7 @@ async function main(args) {
const legacyHeld = process.env[GATE_SLOT_HELD_ENV] === '1';
if (scopedMarker) {
const inherited = inheritedGateSlot({ root: process.cwd(), browser });
- if (inherited) run(gateSlotEnvironment(inherited));
+ if (inherited) await run(gateSlotEnvironment(inherited));
else await acquire();
} else if (legacyHeld) {
throw new Error('this legacy gate marker does not identify a live machine gate lease; restart the parent runner with a scoped gate lease');
@@ -481,4 +1053,13 @@ if (process.argv[1] && resolve(process.argv[1]) === runner) {
} else if (process.argv[1]) {
process.env.PULLBOARD_TEST_FILE = process.argv[1];
installTestWatchdog();
+ const startsPath = process.env[LANDING_WORKER_STARTS_ENV];
+ const attempt = process.env[LANDING_ATTEMPT_ENV];
+ if (startsPath && attempt) {
+ const identity = await landingWorkerIdentity(process.pid);
+ if (!identity) throw new Error('landing test worker could not prove its process identity');
+ appendFileSync(startsPath, `${JSON.stringify({ type: 'worker', attempt, file: resolve(process.argv[1]),
+ pid: identity.pid, pgid: identity.pgid, started: identity.started })}\n`);
+ watchLandingChildSpawns(startsPath, attempt);
+ }
}
diff --git a/docs/api.md b/docs/api.md
index f0203ac7..84f38a2d 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -307,6 +307,8 @@ Row approval and decline first record the person's exact decision through the sa
`pullboard land [--max N] [--dry-run] [--adopt]` is coordinator-only. It merges verified items in verdict order in a separate landing worktree, gates the batch once and records pushed merges. Conflicts and stacked unverified items are named separately. Reproducible failures are bisected; a failing file which passes alone files one flake and holds the batch without retries. Resume includes `landingBatches`, each with its state, owner, exact tip, items and log path.
+The landing gate sets `PULLBOARD_LANDING_RUN=1` only for its test runner. In that mode, the runner requires process isolation and POSIX process identities; it stops scheduling files after the first test-file failure, interrupts files already running, and reports the failure, interrupted files, and selected files not run. Landing early-stop fails before starting tests on Windows because the runner cannot safely identify and drain owned worker descendants there. It uses Node's execution-ordered test completion events; ordinary focused runs and all non-landing gates keep normal scheduling. The runner clears this marker for test workers and nested commands.
+
Only the person can run `pullboard land --waive <test> --until <date> --reason "why"`. A waiver retains every test in the full gate. The batch records its exact tree and each failing test with its covering live waiver; pre-push validates that distinct proof and creates no ordinary green stamp. Expired waivers cannot authorize a push. Existing gate-stamped pushes and `pullboard merged` remain available.
diff --git a/src/gate.js b/src/gate.js
index 765f004b..e5b1903d 100644
--- a/src/gate.js
+++ b/src/gate.js
@@ -19,6 +19,7 @@ import { timingFromOutput, timingRunner } from './timing.js';
const STAMP = 'pullboard-gate-green';
const LOG = 'pullboard-gate.log';
+const LANDING_RUN_ENV = 'PULLBOARD_LANDING_RUN';
const DIGEST_CHARS = 3000;
const TAIL_CHARS = 1000;
const LINE_CHARS = 300;
@@ -130,16 +131,19 @@ function safeLog(output) {
/** Run the unchanged caller command and profile only timings already present in its output.
* @param {string} root
* @param {string} command
- * @param {{ waitMs?: number, artifactDirectory?: string, artifactPrefix?: string, persistLog?: boolean, profileFile?: string, pipefail?: boolean, gateSlotHeld?: boolean, gateLease?: object }} [options]
+ * @param {{ waitMs?: number, artifactDirectory?: string, artifactPrefix?: string, persistLog?: boolean, profileFile?: string, pipefail?: boolean, gateSlotHeld?: boolean, gateLease?: object, landing?: boolean }} [options]
*/
-export function runProfiledShell(root, command, { waitMs = 0, artifactDirectory, artifactPrefix = 'pullboard-gate', persistLog = false, profileFile, pipefail = false, gateSlotHeld = false, gateLease } = {}) {
+export function runProfiledShell(root, command, { waitMs = 0, artifactDirectory, artifactPrefix = 'pullboard-gate', persistLog = false, profileFile, pipefail = false, gateSlotHeld = false, gateLease, landing = false } = {}) {
const directory = artifactDirectory ?? dirname(gitPath(root, LOG));
mkdirSync(directory, { recursive: true, mode: 0o700 });
const id = randomUUID();
const profilePath = profileFile ?? join(directory, `${artifactPrefix}-${id}.profile.json`);
const logPath = persistLog ? join(directory, `${artifactPrefix}-${id}.log`) : null;
const started = Date.now();
- const inherited = gateLease ? gateSlotEnvironment(gateLease) : gateSlotHeld ? { [GATE_SLOT_HELD_ENV]: '1' } : {};
+ const inherited = {
+ ...(gateLease ? gateSlotEnvironment(gateLease) : gateSlotHeld ? { [GATE_SLOT_HELD_ENV]: '1' } : {}),
+ [LANDING_RUN_ENV]: landing ? '1' : '0',
+ };
const run = runShell(root, command, { pipefail, env: inherited });
const profile = writeTimingProfile(profilePath, {
...timingFromOutput(run.output, timingRunner(command)),
@@ -152,12 +156,15 @@ export function runProfiledShell(root, command, { waitMs = 0, artifactDirectory,
/** Run an independent focused comparison without blocking other holders of the machine pool.
* @param {string} root
* @param {string} command
- * @param {{ waitMs?: number, gateSlotHeld?: boolean, gateLease?: object }} [options]
+ * @param {{ waitMs?: number, gateSlotHeld?: boolean, gateLease?: object, landing?: boolean }} [options]
* @returns {Promise<object>} The unchanged shell verdict and its private timing profile.
*/
-export async function runProfiledShellAsync(root, command, { waitMs = 0, gateSlotHeld = false, gateLease } = {}) {
+export async function runProfiledShellAsync(root, command, { waitMs = 0, gateSlotHeld = false, gateLease, landing = false } = {}) {
const started = Date.now();
- const inherited = gateLease ? gateSlotEnvironment(gateLease) : gateSlotHeld ? { [GATE_SLOT_HELD_ENV]: '1' } : {};
+ const inherited = {
+ ...(gateLease ? gateSlotEnvironment(gateLease) : gateSlotHeld ? { [GATE_SLOT_HELD_ENV]: '1' } : {}),
+ [LANDING_RUN_ENV]: landing ? '1' : '0',
+ };
const env = { ...gitChildEnv(root), ...inherited };
const child = spawn(`(\n${command}\n) 2>&1`, { cwd: root, env, shell: true, stdio: ['ignore', 'pipe', 'pipe'] });
const chunks = [];
@@ -286,16 +293,16 @@ export async function runGate(root, config, { trustStamp = true, onWait, landing
throw new Refused('NO_GATE', 'no gate configured; set "gate" in pullboard.json, e.g. "npm test"');
}
if (trustStamp && isStampedGreen(root)) return { isGreen: true, isCached: true, output: '', seconds: 0, log: '' };
- return await withGateSlot(root, (lease) => fullGateRun(root, config, trustStamp, { waitMs: lease.waitMs, gateLease: lease }), {
+ return await withGateSlot(root, (lease) => fullGateRun(root, config, trustStamp, { waitMs: lease.waitMs, gateLease: lease, landing }), {
landing, browser: true, agent, item, kind: landing ? 'landing' : 'gate', onWait,
});
}
/** Run a full gate while its caller owns the queue lease; only a full run may stamp its tree. */
-function fullGateRun(root, config, trustStamp = false, { waitMs = 0, log = gitPath(root, LOG), gateLease } = {}) {
+function fullGateRun(root, config, trustStamp = false, { waitMs = 0, log = gitPath(root, LOG), gateLease, landing = false } = {}) {
if (trustStamp && isStampedGreen(root)) return { isGreen: true, isCached: true, output: '', seconds: 0, log: '' };
const before = committedTree(root);
- const { isGreen, output, seconds, profile, profilePath } = runProfiledShell(root, config.gate, { waitMs, pipefail: true, profileFile: `${log}.profile.json`, gateLease });
+ const { isGreen, output, seconds, profile, profilePath } = runProfiledShell(root, config.gate, { waitMs, pipefail: true, profileFile: `${log}.profile.json`, gateLease, landing });
writeFileSync(log, output);
if (isGreen && before !== null && committedTree(root) === before) writeFileSync(gitPath(root, STAMP), `${before}\n`);
return { isGreen, isCached: false, output, seconds, log, profile, profilePath };
diff --git a/test/run-tests.test.js b/test/run-tests.test.js
index 7a446166..0c4c528c 100644
--- a/test/run-tests.test.js
+++ b/test/run-tests.test.js
@@ -1,10 +1,10 @@
/** Exercise native test-file sharding through the production test runner [C7]. */
import assert from 'node:assert/strict';
-import { execFileSync } from 'node:child_process';
-import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { execFileSync, spawn } from 'node:child_process';
+import { chmodSync, copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { fileURLToPath } from 'node:url';
+import { delimiter, join } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
import { test } from 'node:test';
import { startFixtureChild, runFixtureChild } from './fixture-child.js';
import { listResources } from '../src/resources.js';
@@ -20,6 +20,74 @@ function stageFixtureTests(root, paths) {
execFileSync('git', ['add', '--', ...paths], { cwd: root, stdio: 'ignore' });
}
+/** Treat a reaped or zombie fixture PID as drained while waiting for it to stop executing. */
+async function waitForFixtureProcessDrain(pid, timeoutMs = 2000) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ try {
+ const state = execFileSync('ps', ['-p', String(pid), '-o', 'stat='], { encoding: 'utf8' }).trim();
+ if (!state || state.startsWith('Z')) return true;
+ } catch { return true; }
+ await new Promise(resolve => setTimeout(resolve, 25));
+ }
+ return false;
+}
+
+/** Wait until a fixture PID is executing rather than stopped or reaped. */
+async function waitForFixtureProcessRunning(pid, timeoutMs = 2000) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ try {
+ const state = execFileSync('ps', ['-p', String(pid), '-o', 'stat='], { encoding: 'utf8' }).trim();
+ if (state && !state.startsWith('Z')) return true;
+ } catch { return false; }
+ await new Promise(resolve => setTimeout(resolve, 25));
+ }
+ return false;
+}
+
+/** Capture a fixture's PID, process group, and start identity for safe later cleanup. */
+function fixtureProcessIdentity(pid) {
+ let output;
+ try { output = execFileSync('ps', ['-p', String(pid), '-o', 'pid=,pgid=,stat=,lstart='], { encoding: 'utf8' }).trim(); }
+ catch (error) { if (error.status === 1) return null; throw error; }
+ const match = output.match(/^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.+)$/u);
+ if (!match) return null;
+ return { pid: Number(match[1]), pgid: Number(match[2]), state: match[3], started: match[4] };
+}
+
+/** Signal a fixture only while its captured PID, process group, and start identity still match. */
+function signalFixtureProcess(identity, signal) {
+ try {
+ const current = fixtureProcessIdentity(identity.pid);
+ if (!current) return;
+ if (current.pid === identity.pid && current.pgid === identity.pgid && current.started === identity.started && !current.state.startsWith('Z')) {
+ process.kill(identity.pid, signal);
+ }
+ } catch (error) { if (error.code !== 'ESRCH') throw error; }
+}
+
+/** Treat disappearance, a zombie, or a changed process identity as drained. */
+async function waitForFixtureIdentityDrain(identity, timeoutMs = 2000) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ try {
+ const current = fixtureProcessIdentity(identity.pid);
+ if (!current) return true;
+ if (current.pgid !== identity.pgid || current.started !== identity.started || current.state.startsWith('Z')) return true;
+ } catch (error) { if (error.code === 'ESRCH' || error.status === 1) return true; throw error; }
+ await new Promise(resolve => setTimeout(resolve, 25));
+ }
+ return false;
+}
+
+/** Wait for a fixture's causal file handshake, with a ceiling used only to expose a hung child. */
+async function waitForFixtureMarker(path, label, timeoutMs = 10000) {
+ const deadline = Date.now() + timeoutMs;
+ while (!existsSync(path) && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 10));
+ assert.ok(existsSync(path), `${label} before the fixture hang ceiling`);
+}
+
/** Build a private runner checkout whose tests record the files Node actually selects. */
function makeShardFixture(t) {
const root = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-test-shards-')));
@@ -52,6 +120,560 @@ test('record ${name} [C7]', recordSelectedFile);
return { root, capture, expected, runner: join(bin, 'run-tests.js') };
}
+/** Build a fixture with one held sibling, one failure, and queued sentinels beyond worker capacity. */
+function makeLandingStopFixture(t) {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-landing-stop-')));
+ const bin = join(root, 'bin');
+ const tests = join(root, 'test');
+ const source = fileURLToPath(new URL('../src', import.meta.url));
+ mkdirSync(bin);
+ mkdirSync(tests);
+ writeFileSync(join(root, 'package.json'), JSON.stringify({ type: 'module' }));
+ copyFileSync(runner, join(bin, 'run-tests.js'));
+ cpSync(source, join(root, 'src'), { recursive: true });
+ writeFileSync(join(tests, '01-sibling.test.js'), `import { existsSync, writeFileSync } from 'node:fs';
+import { spawn } from 'node:child_process';
+import { test } from 'node:test';
+test('long sibling begins and remains active', async (t) => {
+ const child = spawn(process.execPath, ['-e', "const fs=require('node:fs'); process.on('SIGTERM', () => { fs.writeFileSync(process.env.PULLBOARD_C7_CHILD_DRAINED, 'drained'); setTimeout(() => process.exit(0), 10); }); fs.writeFileSync(process.env.PULLBOARD_C7_CHILD_READY, 'ready'); setInterval(() => {}, 1000);"], { detached: true, stdio: 'ignore' });
+ child.unref();
+ writeFileSync(process.env.PULLBOARD_C7_CHILD_PID, String(child.pid));
+ t.after(() => { try { process.kill(child.pid, 'SIGTERM'); } catch (error) { if (error.code !== 'ESRCH') throw error; } });
+ const childDeadline = Date.now() + 10000;
+ while (!existsSync(process.env.PULLBOARD_C7_CHILD_READY) && Date.now() < childDeadline) await new Promise(resolve => setTimeout(resolve, 10));
+ if (!existsSync(process.env.PULLBOARD_C7_CHILD_READY)) throw new Error('detached child never became ready');
+ writeFileSync(process.env.PULLBOARD_C7_SIBLING_STARTED, 'started');
+ const releaseDeadline = Date.now() + 10000;
+ while (!existsSync(process.env.PULLBOARD_C7_RELEASE) && Date.now() < releaseDeadline) await new Promise(resolve => setTimeout(resolve, 10));
+ if (!existsSync(process.env.PULLBOARD_C7_RELEASE)) throw new Error('queued sentinel did not release the sibling');
+ writeFileSync(process.env.PULLBOARD_C7_SIBLING_FINISHED, 'finished');
+});
+`);
+ const lateChildCode = `const fs=require('node:fs'); process.on('SIGTERM',()=>{fs.writeFileSync(process.env.PULLBOARD_C7_LATE_CHILD_DRAINED,'drained')}); fs.writeFileSync(process.env.PULLBOARD_C7_LATE_CHILD_READY,'ready'); setInterval(()=>{if(fs.existsSync(process.env.PULLBOARD_C7_LATE_CHILD_RELEASE))process.exit(0)},10);`;
+ const failingChildCode = `const fs=require('node:fs'); const {spawn}=require('node:child_process'); let lateSpawned=false; process.on('SIGTERM', () => { fs.writeFileSync(process.env.PULLBOARD_C7_FAIL_CHILD_DRAINED, 'drained'); if (process.env.PULLBOARD_C7_SPAWN_LATE_CHILD_ON_TERM === '1') { if (lateSpawned) return; lateSpawned=true; const late = spawn(process.execPath, ['-e', ${JSON.stringify(lateChildCode)}], {detached:true,stdio:'ignore'}); late.unref(); fs.writeFileSync(process.env.PULLBOARD_C7_LATE_CHILD_PID, String(late.pid)); const wait=setInterval(()=>{if(fs.existsSync(process.env.PULLBOARD_C7_LATE_CHILD_READY)&&fs.existsSync(process.env.PULLBOARD_C7_FAIL_CHILD_RELEASE)){clearInterval(wait);process.exit(0)}},10); return; } if (process.env.PULLBOARD_C7_HOLD_FAIL_CHILD === '1') { const wait=setInterval(() => { if (fs.existsSync(process.env.PULLBOARD_C7_FAIL_CHILD_RELEASE)) { clearInterval(wait); process.exit(0); } }, 10); } else setTimeout(() => process.exit(0), 10); }); fs.writeFileSync(process.env.PULLBOARD_C7_FAIL_CHILD_READY, 'ready'); setInterval(() => {}, 1000); setTimeout(() => process.exit(0), 15000);`;
+ writeFileSync(join(tests, '02-failing.test.js'), `import assert from 'node:assert/strict';
+import { existsSync, writeFileSync } from 'node:fs';
+import { spawn } from 'node:child_process';
+import { test } from 'node:test';
+test('later file fails after sibling starts', async () => {
+ writeFileSync(process.env.PULLBOARD_C7_WORKER_MARKER, process.env.PULLBOARD_LANDING_RUN ?? '<unset>');
+ const deadline = Date.now() + 10000;
+ while (!existsSync(process.env.PULLBOARD_C7_SIBLING_STARTED) && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 10));
+ if (!existsSync(process.env.PULLBOARD_C7_SIBLING_STARTED)) throw new Error('sibling never started');
+ const child = spawn(process.execPath, ['-e', ${JSON.stringify(failingChildCode)}], { detached: true, stdio: 'ignore' });
+ child.unref();
+ writeFileSync(process.env.PULLBOARD_C7_FAIL_CHILD_PID, String(child.pid));
+ const childDeadline = Date.now() + 10000;
+ while (!existsSync(process.env.PULLBOARD_C7_FAIL_CHILD_READY) && Date.now() < childDeadline) await new Promise(resolve => setTimeout(resolve, 10));
+ if (!existsSync(process.env.PULLBOARD_C7_FAIL_CHILD_READY)) throw new Error('failing worker detached child never became ready');
+ writeFileSync(process.env.PULLBOARD_C7_FAILURE, 'failed');
+ assert.fail('intentional landing stop [C7]');
+});
+`);
+ const queuedFiles = [];
+ for (let number = 3; number <= 8; number += 1) {
+ const name = `${String(number).padStart(2, '0')}-queued.test.js`;
+ queuedFiles.push(`test/${name}`);
+ writeFileSync(join(tests, name), `import { writeFileSync } from 'node:fs';
+import { test } from 'node:test';
+test('queued sentinel ${number} releases ordinary sibling', () => {
+ writeFileSync(process.env.PULLBOARD_C7_QUEUED, '${number}');
+ writeFileSync(process.env.PULLBOARD_C7_RELEASE, 'released');
+});
+`);
+ }
+ t.after(() => rmSync(root, { recursive: true, force: true }));
+ return {
+ root, runner: join(bin, 'run-tests.js'),
+ siblingStarted: join(root, 'sibling-started'), siblingFinished: join(root, 'sibling-finished'),
+ failure: join(root, 'failure'), queued: join(root, 'queued'), queuedFiles, workerMarker: join(root, 'worker-marker'),
+ release: join(root, 'release'),
+ childReady: join(root, 'child-ready'), childPid: join(root, 'child-pid'), childDrained: join(root, 'child-drained'),
+ failChildReady: join(root, 'fail-child-ready'), failChildPid: join(root, 'fail-child-pid'), failChildDrained: join(root, 'fail-child-drained'),
+ failChildRelease: join(root, 'fail-child-release'),
+ lateChildReady: join(root, 'late-child-ready'), lateChildPid: join(root, 'late-child-pid'),
+ lateChildDrained: join(root, 'late-child-drained'), lateChildRelease: join(root, 'late-child-release'),
+ };
+}
+
+/** Emulate a reused worker PID in ps output without changing any real process identity. */
+function installLandingPidReusePsShim(fixture, unrelatedPid) {
+ const bin = join(fixture.root, 'pid-reuse-bin');
+ mkdirSync(bin);
+ const realPs = execFileSync('which', ['ps'], { encoding: 'utf8' }).trim();
+ const source = `#!/usr/bin/env node
+import { execFileSync } from 'node:child_process';
+import { existsSync, readFileSync, writeFileSync } from 'node:fs';
+const realPs = ${JSON.stringify(realPs)};
+const args = process.argv.slice(2);
+const target = '-axo pid=,ppid=,pgid=,stat=,lstart=,command=';
+const output = execFileSync(realPs, args, { encoding: 'utf8' });
+if (args.join(' ') !== target) { process.stdout.write(output); process.exit(0); }
+function parse(line) {
+ const match = line.match(/^\\s*(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\S+)\\s+(.+)$/u);
+ if (!match) return null;
+ const fields = match[5].trim().split(/\\s+/u);
+ return { pid: Number(match[1]), ppid: Number(match[2]), pgid: Number(match[3]), state: match[4],
+ started: fields.slice(0, 5).join(' '), command: fields.slice(5).join(' ') };
+}
+function format(row) { return [row.pid, row.ppid, row.pgid, row.state, row.started, row.command].join(' '); }
+let rows = output.split(/\\r?\\n/u).map(parse).filter(Boolean);
+const starts = process.env.PULLBOARD_LANDING_WORKER_STARTS;
+const outsiderPid = ${Number(unrelatedPid)};
+if (starts) {
+ let receipts = [];
+ try { receipts = readFileSync(starts, 'utf8').split(/\\r?\\n/u).filter(Boolean).map(line => JSON.parse(line)); } catch {}
+ for (const receipt of receipts) {
+ if (receipt.type !== 'worker' || receipt.attempt !== process.env.PULLBOARD_LANDING_ATTEMPT) continue;
+ const live = rows.find(row => row.pid === receipt.pid);
+ const same = live && receipt.pgid !== undefined && live.pgid === receipt.pgid && live.started === receipt.started;
+ if (same) continue;
+ rows = rows.filter(row => row.pid !== receipt.pid);
+ rows.push({ pid: receipt.pid, ppid: 1, pgid: receipt.pid, state: 'S',
+ started: 'Tue Oct 13 07:00:00 2026', command: 'fixture-reused-worker-pid' });
+ const outsider = rows.find(row => row.pid === outsiderPid);
+ if (outsider) outsider.ppid = receipt.pid;
+ const injected = process.env.PULLBOARD_C7_PID_REUSE_INJECTED;
+ if (injected && !existsSync(injected)) writeFileSync(injected, 'injected');
+ }
+}
+process.stdout.write(rows.map(format).join('\\n') + '\\n');
+`;
+ const path = join(bin, 'ps');
+ writeFileSync(path, source);
+ chmodSync(path, 0o755);
+ return bin;
+}
+
+/** Fail one owned SIGTERM in the gate runner, then let later retries reach the real child. */
+function installLandingSignalFailureShim(fixture) {
+ const path = join(fixture.root, 'fail-one-owned-signal.mjs');
+ writeFileSync(path, `import { existsSync, readFileSync, writeFileSync } from 'node:fs';
+if (process.argv[1] === process.env.PULLBOARD_C7_RUNNER_PATH) {
+ const original = process.kill.bind(process);
+ let failed = false;
+ process.kill = (pid, signal) => {
+ const pidFile = process.env.PULLBOARD_C7_FAIL_CHILD_PID;
+ if (!failed && signal === 'SIGTERM' && pidFile && existsSync(pidFile) && Number(readFileSync(pidFile, 'utf8').trim()) === Number(pid)) {
+ failed = true;
+ writeFileSync(process.env.PULLBOARD_C7_SIGNAL_FAILURE, 'injected');
+ const error = new Error('injected one-shot signal failure');
+ error.code = 'EPERM';
+ throw error;
+ }
+ return original(pid, signal);
+ };
+}
+`);
+ return path;
+}
+
+test('a green landing run retries transient process snapshot timeouts [C7,V4]', async t => {
+ const fixture = makeShardFixture(t);
+ const ready = join(fixture.root, 'snapshot-ready');
+ const sampled = join(fixture.root, 'sample-timeout');
+ const drained = join(fixture.root, 'drain-timeout');
+ const childReady = join(fixture.root, 'child-ready');
+ const childDrained = join(fixture.root, 'child-drained');
+ const childIdentity = join(fixture.root, 'child-identity.json');
+ t.after(() => {
+ if (existsSync(childIdentity)) signalFixtureProcess(JSON.parse(readFileSync(childIdentity, 'utf8')), 'SIGKILL');
+ });
+ const preload = join(fixture.root, 'snapshot-timeout.mjs');
+ writeFileSync(preload, `import childProcess from 'node:child_process';
+import { syncBuiltinESMExports } from 'node:module';
+import { existsSync, writeFileSync } from 'node:fs';
+if (process.argv[1] === ${JSON.stringify(fixture.runner)}) {
+ const original = childProcess.execFileSync;
+ childProcess.execFileSync = (command, args, options) => {
+ if (command === 'ps' && args?.[0] === '-axo' && existsSync(${JSON.stringify(ready)})) {
+ const duringDrain = new Error().stack.includes('at snapshot ');
+ const marker = duringDrain ? ${JSON.stringify(drained)} : ${JSON.stringify(sampled)};
+ if (!existsSync(marker)) {
+ writeFileSync(marker, 'injected');
+ const error = new Error('injected process snapshot timeout');
+ error.code = 'ETIMEDOUT';
+ throw error;
+ }
+ }
+ return original(command, args, options);
+ };
+ syncBuiltinESMExports();
+}
+`);
+ const childCode = `const {writeFileSync}=require('node:fs'); const {execFileSync}=require('node:child_process');
+const fields=execFileSync('ps',['-p',String(process.pid),'-o','pid=,pgid=,stat=,lstart='],{encoding:'utf8'}).trim().split(/\\s+/);
+writeFileSync(${JSON.stringify(childIdentity)},JSON.stringify({pid:Number(fields[0]),pgid:Number(fields[1]),state:fields[2],started:fields.slice(3).join(' ')}));
+process.on('SIGTERM',()=>{writeFileSync(${JSON.stringify(childDrained)},'drained');process.exit(0)});
+writeFileSync(${JSON.stringify(childReady)},'ready');setInterval(()=>{},1000);setTimeout(()=>process.exit(0),20000);`;
+ writeFileSync(join(fixture.root, 'test/shard-01.test.js'), `import assert from 'node:assert/strict';
+import { existsSync, writeFileSync } from 'node:fs';
+import { spawn } from 'node:child_process';
+import { test } from 'node:test';
+test('green file waits for the injected observation', async () => {
+ const child = spawn(process.execPath, ['-e', ${JSON.stringify(childCode)}], { detached: true, stdio: 'ignore' });
+ child.unref();
+ const childDeadline = Date.now() + 10000;
+ while (!existsSync(${JSON.stringify(childReady)}) && Date.now() < childDeadline) await new Promise(resolve => setTimeout(resolve, 10));
+ assert.ok(existsSync(${JSON.stringify(childReady)}), 'owned detached child is ready');
+ writeFileSync(${JSON.stringify(ready)}, 'ready');
+ const deadline = Date.now() + 10000;
+ while (!existsSync(${JSON.stringify(sampled)}) && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 10));
+ assert.ok(existsSync(${JSON.stringify(sampled)}), 'the monitor snapshot timeout was injected');
+ assert.equal(existsSync(${JSON.stringify(childDrained)}), false, 'a failed snapshot authorizes no signal while the test is active');
+});
+`);
+ const env = { ...process.env, PULLBOARD_LANDING_RUN: '1',
+ PULLBOARD_MACHINE_HOME: join(fixture.root, 'machine'),
+ NODE_OPTIONS: [process.env.NODE_OPTIONS, '--import=' + pathToFileURL(preload).href].filter(Boolean).join(' ') };
+ for (const key of ['PULLBOARD_GATE_SLOT_HELD', 'PULLBOARD_GATE_SLOT_POOL', 'PULLBOARD_GATE_SLOT_TOKEN', 'PULLBOARD_BROWSER_SLOT_HELD']) delete env[key];
+ const result = runFixtureChild(process.execPath, [fixture.runner, 'test/shard-01.test.js'], {
+ cwd: fixture.root, env, encoding: 'utf8', timeout: 15000,
+ });
+ assert.ok(existsSync(sampled), 'a live monitor observation failed once');
+ assert.ok(existsSync(drained), 'the final ownership census failed once and was retried');
+ assert.equal(result.status, 0, `${result.context}\n${result.stdout ?? ''}\n${result.stderr ?? ''}`);
+ assert.match(result.stdout, /# fail 0/u);
+ assert.ok(existsSync(childDrained), 'the owned child acknowledged cleanup after a successful census');
+ assert.ok(await waitForFixtureIdentityDrain(JSON.parse(readFileSync(childIdentity, 'utf8'))), 'the owned detached child stopped before the gate returned');
+});
+
+test('a landing worker retries its startup identity snapshot timeout [C7,V4]', t => {
+ const fixture = makeShardFixture(t);
+ const injected = join(fixture.root, 'worker-snapshot-timeout');
+ const ran = join(fixture.root, 'worker-test-ran');
+ const workerTest = join(fixture.root, 'test/worker-start.test.js');
+ writeFileSync(workerTest, `import assert from 'node:assert/strict';
+import { readFileSync, writeFileSync } from 'node:fs';
+import { test } from 'node:test';
+test('the test body runs after the worker identity retry', () => {
+ const marker = JSON.parse(readFileSync(${JSON.stringify(injected)}, 'utf8'));
+ const receipts = readFileSync(process.env.PULLBOARD_LANDING_WORKER_STARTS, 'utf8').trim().split(/\\r?\\n/u).map(line => JSON.parse(line));
+ const receipt = receipts.find(row => row.type === 'worker' && row.pid === process.pid);
+ assert.equal(marker.pid, process.pid, 'the timeout was injected into this test worker');
+ assert.match(marker.stack, /landingWorkerIdentity/u, 'the timeout came from worker startup, not parent monitoring');
+ assert.ok(receipt && receipt.file.endsWith('worker-start.test.js') && receipt.pgid && receipt.started, 'the worker recorded a fresh successful identity receipt before test execution');
+ writeFileSync(${JSON.stringify(ran)}, 'ran');
+});
+`);
+ const preload = join(fixture.root, 'worker-snapshot-timeout.mjs');
+ writeFileSync(preload, `import childProcess from 'node:child_process';
+import { syncBuiltinESMExports } from 'node:module';
+import { existsSync, writeFileSync } from 'node:fs';
+if (process.argv[1] !== ${JSON.stringify(fixture.runner)}) {
+ const originalSync = childProcess.execFileSync;
+ const originalExec = childProcess.execFile;
+ let injected = false;
+ function shouldTimeout(command, args) {
+ if (injected || command !== 'ps' || args?.[0] !== '-axo') return false;
+ injected = true;
+ writeFileSync(${JSON.stringify(injected)}, JSON.stringify({ pid: process.pid, stack: new Error().stack }));
+ return true;
+ }
+ childProcess.execFileSync = (command, args, options) => {
+ if (shouldTimeout(command, args)) { const error = new Error('injected worker process snapshot timeout'); error.code = 'ETIMEDOUT'; throw error; }
+ return originalSync(command, args, options);
+ };
+ childProcess.execFile = (command, args, options, callback) => {
+ if (shouldTimeout(command, args)) {
+ const error = new Error('injected worker process snapshot timeout'); error.code = 'ETIMEDOUT';
+ setImmediate(() => callback(error, '', ''));
+ return undefined;
+ }
+ return originalExec(command, args, options, callback);
+ };
+ syncBuiltinESMExports();
+}
+`);
+ const env = { ...process.env, PULLBOARD_LANDING_RUN: '1',
+ PULLBOARD_MACHINE_HOME: join(fixture.root, 'machine'),
+ NODE_OPTIONS: [process.env.NODE_OPTIONS, '--import=' + pathToFileURL(preload).href].filter(Boolean).join(' ') };
+ for (const key of ['PULLBOARD_GATE_SLOT_HELD', 'PULLBOARD_GATE_SLOT_POOL', 'PULLBOARD_GATE_SLOT_TOKEN', 'PULLBOARD_BROWSER_SLOT_HELD']) delete env[key];
+ const result = runFixtureChild(process.execPath, [fixture.runner, 'test/worker-start.test.js'], {
+ cwd: fixture.root, env, encoding: 'utf8', timeout: 25_000,
+ });
+ assert.ok(existsSync(injected), 'the first worker identity snapshot timed out');
+ assert.equal(result.status, 0, `${result.context}\n${result.stdout ?? ''}\n${result.stderr ?? ''}`);
+ assert.ok(existsSync(ran), 'the test file executed after the retry succeeded');
+ assert.match(`${result.stdout ?? ''}${result.stderr ?? ''}`, /worker identity snapshot timed out; retrying before file execution/u);
+ assert.match(result.stdout, /# fail 0/u);
+});
+
+test('a landing run stops at the first failing file [C7,V4]', async t => {
+ const unrelatedRoot = mkdtempSync(join(tmpdir(), 'pullboard-landing-unrelated-'));
+ const unrelatedReady = join(unrelatedRoot, 'ready');
+ const unrelatedDrained = join(unrelatedRoot, 'drained');
+ const unrelated = spawn(process.execPath, ['-e', `const fs=require('node:fs'); process.on('SIGTERM', () => { fs.writeFileSync(${JSON.stringify(unrelatedDrained)}, 'drained'); process.exit(0); }); fs.writeFileSync(${JSON.stringify(unrelatedReady)}, 'ready'); setInterval(() => {}, 1000);`], {
+ detached: true, stdio: 'ignore',
+ });
+ t.after(() => {
+ if (unrelated.exitCode === null && unrelated.signalCode === null) unrelated.kill('SIGKILL');
+ rmSync(unrelatedRoot, { recursive: true, force: true });
+ });
+ const unrelatedDeadline = Date.now() + 2000;
+ while (!existsSync(unrelatedReady) && Date.now() < unrelatedDeadline) await new Promise(resolve => setTimeout(resolve, 10));
+ assert.ok(existsSync(unrelatedReady), 'the unrelated process started before the landing run');
+ const fixture = makeLandingStopFixture(t);
+ const env = {
+ ...process.env,
+ PULLBOARD_MACHINE_HOME: join(fixture.root, 'machine'),
+ PULLBOARD_LANDING_RUN: '1',
+ PULLBOARD_C7_SIBLING_STARTED: fixture.siblingStarted,
+ PULLBOARD_C7_SIBLING_FINISHED: fixture.siblingFinished,
+ PULLBOARD_C7_FAILURE: fixture.failure,
+ PULLBOARD_C7_RELEASE: fixture.release,
+ PULLBOARD_C7_QUEUED: fixture.queued,
+ PULLBOARD_C7_WORKER_MARKER: fixture.workerMarker,
+ PULLBOARD_C7_CHILD_READY: fixture.childReady,
+ PULLBOARD_C7_CHILD_PID: fixture.childPid,
+ PULLBOARD_C7_CHILD_DRAINED: fixture.childDrained,
+ PULLBOARD_C7_FAIL_CHILD_READY: fixture.failChildReady,
+ PULLBOARD_C7_FAIL_CHILD_PID: fixture.failChildPid,
+ PULLBOARD_C7_FAIL_CHILD_DRAINED: fixture.failChildDrained,
+ };
+ for (const key of ['PULLBOARD_GATE_SLOT_HELD', 'PULLBOARD_GATE_SLOT_POOL', 'PULLBOARD_GATE_SLOT_TOKEN', 'PULLBOARD_BROWSER_SLOT_HELD']) delete env[key];
+ const stopped = runFixtureChild(process.execPath, [fixture.runner, '--test-concurrency=2'], {
+ cwd: fixture.root, env, encoding: 'utf8', timeout: 15000,
+ });
+ const stoppedOutput = `${stopped.stdout ?? ''}\n${stopped.stderr ?? ''}`;
+ assert.equal(stopped.status, 1, `${stopped.context}\n${stoppedOutput}`);
+ assert.ok(existsSync(fixture.failure), 'the intentional failing test ran');
+ assert.ok(existsSync(fixture.siblingStarted), 'the earlier sibling was active when failure completed');
+ assert.ok(existsSync(fixture.childReady), 'the active sibling launched its detached child');
+ assert.equal(existsSync(fixture.siblingFinished), false, 'the active sibling was interrupted');
+ assert.equal(existsSync(fixture.queued), false, 'the queued sentinel never started');
+ assert.equal(existsSync(fixture.release), false, 'no queued sentinel released the active sibling');
+ assert.ok(existsSync(fixture.childDrained), 'the detached child handled the runner cleanup signal');
+ assert.ok(await waitForFixtureProcessDrain(readFileSync(fixture.childPid, 'utf8').trim()), 'the detached child exited before the gate returned');
+ assert.ok(existsSync(fixture.failChildReady), 'the failing worker launched its own detached child');
+ assert.ok(existsSync(fixture.failChildDrained), 'the runner captured and drained the failing worker child before it was reparented');
+ assert.ok(await waitForFixtureProcessDrain(readFileSync(fixture.failChildPid, 'utf8').trim()), 'the failing worker child exited before the gate returned');
+ assert.ok(await waitForFixtureProcessRunning(unrelated.pid), 'an unrelated detached process remains alive');
+ assert.equal(existsSync(unrelatedDrained), false, 'the unrelated process received no cleanup signal');
+ unrelated.kill('SIGTERM');
+ assert.ok(await waitForFixtureProcessDrain(unrelated.pid), 'the regression cleaned up its unrelated process');
+ assert.ok(existsSync(unrelatedDrained), 'the unrelated process acknowledged test cleanup');
+ assert.match(stoppedOutput, /Landing gate stopped early after .*02-failing\.test\.js/u);
+ assert.match(stoppedOutput, /Triggering test error:[\s\S]*intentional landing stop \[C7\]/u);
+ assert.match(stoppedOutput, /Files not run: .*0[3-8]-queued\.test\.js/u);
+ assert.equal(readFileSync(fixture.workerMarker, 'utf8'), '0', 'test workers do not inherit the landing mode');
+
+ const inProcess = makeLandingStopFixture(t);
+ const inProcessEnv = {
+ ...env,
+ PULLBOARD_MACHINE_HOME: join(inProcess.root, 'machine'),
+ PULLBOARD_C7_SIBLING_STARTED: inProcess.siblingStarted,
+ PULLBOARD_C7_SIBLING_FINISHED: inProcess.siblingFinished,
+ PULLBOARD_C7_FAILURE: inProcess.failure,
+ PULLBOARD_C7_RELEASE: inProcess.release,
+ PULLBOARD_C7_QUEUED: inProcess.queued,
+ PULLBOARD_C7_WORKER_MARKER: inProcess.workerMarker,
+ PULLBOARD_C7_CHILD_READY: inProcess.childReady,
+ PULLBOARD_C7_CHILD_PID: inProcess.childPid,
+ PULLBOARD_C7_CHILD_DRAINED: inProcess.childDrained,
+ PULLBOARD_C7_FAIL_CHILD_READY: inProcess.failChildReady,
+ PULLBOARD_C7_FAIL_CHILD_PID: inProcess.failChildPid,
+ PULLBOARD_C7_FAIL_CHILD_DRAINED: inProcess.failChildDrained,
+ };
+ const inProcessStopped = runFixtureChild(process.execPath,
+ [inProcess.runner, '--test-isolation=none', '--test-concurrency=2'], {
+ cwd: inProcess.root, env: inProcessEnv, encoding: 'utf8', timeout: 15000,
+ });
+ const inProcessOutput = `${inProcessStopped.stdout ?? ''}\n${inProcessStopped.stderr ?? ''}`;
+ assert.equal(inProcessStopped.status, 1, `${inProcessStopped.context}\n${inProcessOutput}`);
+ assert.match(inProcessOutput, /landing gate early-stop requires --test-isolation=process/u);
+ assert.equal(existsSync(inProcess.siblingStarted), false, 'no-isolation landing was refused before any file started');
+ assert.equal(existsSync(inProcess.queued), false, 'no-isolation landing did not start queued sentinels');
+
+ const ordinary = makeLandingStopFixture(t);
+ const ordinaryEnv = {
+ ...env,
+ PULLBOARD_MACHINE_HOME: join(ordinary.root, 'machine'),
+ PULLBOARD_LANDING_RUN: '0',
+ PULLBOARD_C7_SIBLING_STARTED: ordinary.siblingStarted,
+ PULLBOARD_C7_SIBLING_FINISHED: ordinary.siblingFinished,
+ PULLBOARD_C7_FAILURE: ordinary.failure,
+ PULLBOARD_C7_RELEASE: ordinary.release,
+ PULLBOARD_C7_QUEUED: ordinary.queued,
+ PULLBOARD_C7_WORKER_MARKER: ordinary.workerMarker,
+ PULLBOARD_C7_CHILD_READY: ordinary.childReady,
+ PULLBOARD_C7_CHILD_PID: ordinary.childPid,
+ PULLBOARD_C7_CHILD_DRAINED: ordinary.childDrained,
+ PULLBOARD_C7_FAIL_CHILD_READY: ordinary.failChildReady,
+ PULLBOARD_C7_FAIL_CHILD_PID: ordinary.failChildPid,
+ PULLBOARD_C7_FAIL_CHILD_DRAINED: ordinary.failChildDrained,
+ };
+ const normal = runFixtureChild(process.execPath, [ordinary.runner, '--test-concurrency=2',
+ 'test/01-sibling.test.js', 'test/02-failing.test.js', ...ordinary.queuedFiles], {
+ cwd: ordinary.root, env: ordinaryEnv, encoding: 'utf8', timeout: 20000,
+ });
+ assert.equal(normal.status, 1, normal.context);
+ assert.ok(existsSync(ordinary.siblingFinished), `ordinary runs wait for active sibling files\n${normal.context}\nstdout: ${normal.stdout ?? ''}`);
+ assert.ok(existsSync(ordinary.queued), 'ordinary runs continue scheduling queued files');
+ assert.ok(existsSync(ordinary.childDrained), 'ordinary test cleanup also drains its detached child');
+ assert.ok(await waitForFixtureProcessDrain(readFileSync(ordinary.childPid, 'utf8').trim()), 'ordinary test cleanup waited for its child to stop');
+ assert.ok(existsSync(ordinary.failChildReady), 'the failing worker launched its detached child during an ordinary run');
+ try { process.kill(Number(readFileSync(ordinary.failChildPid, 'utf8').trim()), 'SIGTERM'); }
+ catch (error) { if (error.code !== 'ESRCH') throw error; }
+ assert.ok(await waitForFixtureProcessDrain(readFileSync(ordinary.failChildPid, 'utf8').trim()), 'ordinary fixture child was drained');
+ assert.ok(existsSync(ordinary.failChildDrained), 'the regression cleaned up the ordinary failing-worker child');
+ assert.doesNotMatch(`${normal.stdout ?? ''}\n${normal.stderr ?? ''}`, /stopped early/u);
+
+ await t.test('a reused worker PID cannot adopt an unrelated process subtree', async t => {
+ const outsiderRoot = mkdtempSync(join(tmpdir(), 'pullboard-landing-pid-reuse-'));
+ const outsiderReady = join(outsiderRoot, 'ready');
+ const outsiderDrained = join(outsiderRoot, 'drained');
+ const outsider = spawn(process.execPath, ['-e', `const fs=require('node:fs'); process.on('SIGTERM',()=>{fs.writeFileSync(${JSON.stringify(outsiderDrained)},'drained');process.exit(0)});fs.writeFileSync(${JSON.stringify(outsiderReady)},'ready');setInterval(()=>{},1000);`], {
+ detached: true, stdio: 'ignore',
+ });
+ await waitForFixtureMarker(outsiderReady, 'the unrelated process started');
+ const outsiderIdentity = fixtureProcessIdentity(outsider.pid);
+ assert.ok(outsiderIdentity, 'the unrelated process has a capturable cleanup identity');
+ const cleanupOutsider = async () => {
+ signalFixtureProcess(outsiderIdentity, 'SIGTERM');
+ await waitForFixtureIdentityDrain(outsiderIdentity);
+ rmSync(outsiderRoot, { recursive: true, force: true });
+ };
+ t.after(cleanupOutsider);
+
+ const reused = makeLandingStopFixture(t);
+ const psShim = installLandingPidReusePsShim(reused, outsider.pid);
+ const injected = join(reused.root, 'pid-reuse-injected');
+ const env = {
+ ...process.env,
+ PATH: [psShim, process.env.PATH].filter(Boolean).join(delimiter),
+ PULLBOARD_MACHINE_HOME: join(reused.root, 'machine'),
+ PULLBOARD_LANDING_RUN: '1',
+ PULLBOARD_C7_UNRELATED_PID: String(outsider.pid),
+ PULLBOARD_C7_PID_REUSE_INJECTED: injected,
+ PULLBOARD_C7_SIBLING_STARTED: reused.siblingStarted,
+ PULLBOARD_C7_SIBLING_FINISHED: reused.siblingFinished,
+ PULLBOARD_C7_FAILURE: reused.failure,
+ PULLBOARD_C7_RELEASE: reused.release,
+ PULLBOARD_C7_QUEUED: reused.queued,
+ PULLBOARD_C7_WORKER_MARKER: reused.workerMarker,
+ PULLBOARD_C7_CHILD_READY: reused.childReady,
+ PULLBOARD_C7_CHILD_PID: reused.childPid,
+ PULLBOARD_C7_CHILD_DRAINED: reused.childDrained,
+ PULLBOARD_C7_FAIL_CHILD_READY: reused.failChildReady,
+ PULLBOARD_C7_FAIL_CHILD_PID: reused.failChildPid,
+ PULLBOARD_C7_FAIL_CHILD_DRAINED: reused.failChildDrained,
+ };
+ for (const key of ['PULLBOARD_GATE_SLOT_HELD', 'PULLBOARD_GATE_SLOT_POOL', 'PULLBOARD_GATE_SLOT_TOKEN', 'PULLBOARD_BROWSER_SLOT_HELD']) delete env[key];
+ const result = runFixtureChild(process.execPath, [reused.runner, '--test-concurrency=2'], {
+ cwd: reused.root, env, encoding: 'utf8', timeout: 15000,
+ });
+ assert.equal(result.status, 1, `${result.context}\n${result.stdout ?? ''}\n${result.stderr ?? ''}`);
+ assert.ok(existsSync(injected), 'the process-table fixture presented an old worker PID with a different start identity');
+ assert.ok(await waitForFixtureProcessRunning(outsider.pid), 'the unrelated process stayed alive after stale-root cleanup');
+ assert.equal(existsSync(outsiderDrained), false, 'a reused worker PID did not adopt and signal the unrelated subtree');
+ assert.ok(existsSync(reused.failChildDrained), 'the runner still drained its actual failing worker child');
+ });
+
+ await t.test('a failed cleanup signal keeps the gate slot until its child exits', async t => {
+ const held = makeLandingStopFixture(t);
+ const machine = join(held.root, 'machine');
+ mkdirSync(machine);
+ writeFileSync(join(machine, 'settings.json'), JSON.stringify({ gateSlots: 1 }));
+ const signalFailure = join(held.root, 'signal-failure');
+ const shim = installLandingSignalFailureShim(held);
+ const baseEnv = {
+ ...process.env,
+ PULLBOARD_MACHINE_HOME: machine,
+ PULLBOARD_LANDING_RUN: '1',
+ PULLBOARD_C7_HOLD_FAIL_CHILD: '1',
+ PULLBOARD_C7_SPAWN_LATE_CHILD_ON_TERM: '1',
+ PULLBOARD_C7_RUNNER_PATH: held.runner,
+ PULLBOARD_C7_SIGNAL_FAILURE: signalFailure,
+ PULLBOARD_C7_FAIL_CHILD_RELEASE: held.failChildRelease,
+ PULLBOARD_C7_SIBLING_STARTED: held.siblingStarted,
+ PULLBOARD_C7_SIBLING_FINISHED: held.siblingFinished,
+ PULLBOARD_C7_FAILURE: held.failure,
+ PULLBOARD_C7_RELEASE: held.release,
+ PULLBOARD_C7_QUEUED: held.queued,
+ PULLBOARD_C7_WORKER_MARKER: held.workerMarker,
+ PULLBOARD_C7_CHILD_READY: held.childReady,
+ PULLBOARD_C7_CHILD_PID: held.childPid,
+ PULLBOARD_C7_CHILD_DRAINED: held.childDrained,
+ PULLBOARD_C7_FAIL_CHILD_READY: held.failChildReady,
+ PULLBOARD_C7_FAIL_CHILD_PID: held.failChildPid,
+ PULLBOARD_C7_FAIL_CHILD_DRAINED: held.failChildDrained,
+ PULLBOARD_C7_LATE_CHILD_READY: held.lateChildReady,
+ PULLBOARD_C7_LATE_CHILD_PID: held.lateChildPid,
+ PULLBOARD_C7_LATE_CHILD_DRAINED: held.lateChildDrained,
+ PULLBOARD_C7_LATE_CHILD_RELEASE: held.lateChildRelease,
+ NODE_OPTIONS: [process.env.NODE_OPTIONS, `--import=${pathToFileURL(shim).href}`].filter(Boolean).join(' '),
+ };
+ for (const key of ['PULLBOARD_GATE_SLOT_HELD', 'PULLBOARD_GATE_SLOT_POOL', 'PULLBOARD_GATE_SLOT_TOKEN', 'PULLBOARD_BROWSER_SLOT_HELD']) delete baseEnv[key];
+
+ const landing = startFixtureChild(process.execPath, [held.runner, '--test-concurrency=2'], {
+ cwd: held.root, env: baseEnv, stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ let landingOutput = '';
+ landing.stdout?.setEncoding('utf8').on('data', part => { landingOutput += part; });
+ landing.stderr?.setEncoding('utf8').on('data', part => { landingOutput += part; });
+ const landingClosed = new Promise(resolve => landing.once('close', (code, signal) => resolve({ code, signal })));
+ let waiter;
+ let waiterClosed;
+ let waiterStarted = false;
+ let failChildIdentity = null;
+ let lateChildIdentity = null;
+ try {
+ await waitForFixtureMarker(held.failChildReady, 'the failing file launched its held child');
+ failChildIdentity = fixtureProcessIdentity(readFileSync(held.failChildPid, 'utf8').trim());
+ assert.ok(failChildIdentity, 'the owned child has a capturable cleanup identity');
+ const waiterReadyFile = join(held.root, 'competing-gate-started');
+ const resourceModule = fileURLToPath(new URL('../src/resources.js', import.meta.url));
+ const waiterSource = `import { takeResource } from ${JSON.stringify(resourceModule)}; import { writeFileSync } from 'node:fs'; const lease = await takeResource({ name: 'gate', capacity: 1, scope: 'machine', root: ${JSON.stringify(held.root)}, agent: 'cleanup-drain-waiter' }); writeFileSync(${JSON.stringify(waiterReadyFile)}, 'started'); lease.release();`;
+ waiter = startFixtureChild(process.execPath, ['--input-type=module', '-e', waiterSource], {
+ cwd: held.root, env: baseEnv, stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ waiterClosed = new Promise(resolve => waiter.once('close', (code, signal) => resolve({ code, signal })));
+
+ let queued = false;
+ const handshakeDeadline = Date.now() + 10000;
+ while (!existsSync(held.lateChildDrained) && !existsSync(waiterReadyFile) && Date.now() < handshakeDeadline) {
+ await new Promise(resolve => setTimeout(resolve, 10));
+ }
+ assert.ok(existsSync(signalFailure), 'the first owned SIGTERM failed as injected');
+ assert.ok(existsSync(held.failChildDrained), 'the original owned child handled TERM and spawned a late detached child');
+ assert.ok(existsSync(held.lateChildReady), 'the late detached child reached its ready handshake');
+ assert.ok(existsSync(held.lateChildDrained), 'the live receipt set grew and cleanup reached the late child');
+ lateChildIdentity = fixtureProcessIdentity(readFileSync(held.lateChildPid, 'utf8').trim());
+ assert.ok(lateChildIdentity, 'the late child has a capturable cleanup identity');
+ assert.equal(existsSync(waiterReadyFile), false, 'no competing gate action started while descendant drain was unresolved');
+ const queueDeadline = Date.now() + 10000;
+ while (!queued && !existsSync(waiterReadyFile) && Date.now() < queueDeadline) {
+ queued = focusedPoolSnapshot(machine)?.line.some(row => row.agent === 'cleanup-drain-waiter') ?? false;
+ if (!queued) await new Promise(resolve => setTimeout(resolve, 10));
+ }
+ assert.ok(queued, 'the competing gate action appeared in the queue while the late child remained held');
+ assert.equal(existsSync(waiterReadyFile), false, 'the queued gate action has not entered before the child release');
+
+ writeFileSync(held.lateChildRelease, 'allow exit');
+ writeFileSync(held.failChildRelease, 'allow exit');
+ const [landingResult, waiterResult] = await Promise.all([landingClosed, waiterClosed]);
+ waiterStarted = existsSync(waiterReadyFile);
+ assert.equal(landingResult.code, 1, `${landingOutput}\n${landingResult.signal ?? ''}`);
+ assert.equal(landingResult.signal, null);
+ assert.ok(landingOutput.includes('owned descendants drained after cleanup error: injected one-shot signal failure'), landingOutput);
+ assert.deepEqual(waiterResult, { code: 0, signal: null });
+ assert.ok(waiterStarted, 'the queued gate action started after owned child exit was confirmed');
+ } finally {
+ try { writeFileSync(held.failChildRelease, 'allow exit'); } catch { /* Fixture teardown may already remove it. */ }
+ try { writeFileSync(held.lateChildRelease, 'allow exit'); } catch { /* Fixture teardown may already remove it. */ }
+ if (failChildIdentity) signalFixtureProcess(failChildIdentity, 'SIGTERM');
+ if (lateChildIdentity) signalFixtureProcess(lateChildIdentity, 'SIGTERM');
+ if (landing.exitCode === null && landing.signalCode === null) landing.kill('SIGTERM');
+ if (waiter && waiter.exitCode === null && waiter.signalCode === null) waiter.kill('SIGTERM');
+ if (landingClosed) await Promise.race([landingClosed, new Promise(resolve => setTimeout(resolve, 2000))]);
+ if (waiterClosed) await Promise.race([waiterClosed, new Promise(resolve => setTimeout(resolve, 2000))]);
+ if (failChildIdentity) await waitForFixtureIdentityDrain(failChildIdentity);
+ if (lateChildIdentity) await waitForFixtureIdentityDrain(lateChildIdentity);
+ }
+ });
+});
+
/** Build a copied production runner with tracked, ignored, and untracked test files. */
function makeTrackedSelectionFixture(t) {
const root = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-tracked-tests-')));