Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
feat(test): lend tokens through explicit async waits [C7]
Corey Olson72b933d91aaa
diff --git a/src/test-file-pool.js b/src/test-file-pool.jsindex a0802c8f..78af2603 100644--- a/src/test-file-pool.js+++ b/src/test-file-pool.js@@ -8,15 +8,23 @@* A test file that starts a nested run with a synchronous call is blocked until that call returns, so it lends its* place for the call: the call's files fill that place one at a time and never take a second core, and the call* returns only after the last of them exits, so the file resumes into its own place. Nothing it starts can wait- * forever on the token it holds. A run started asynchronously, or left behind by the call, borrows nothing.+ * forever on the token it holds. An asynchronous run borrows nothing until its parent explicitly promises to yield through awaitNestedRun.+ * A run left behind by a completed call borrows nothing.*/import { randomUUID } from 'node:crypto';+import { errorMonitor } from 'node:events';import { mkdirSync } from 'node:fs';import childProcess from 'node:child_process';import { syncBuiltinESMExports } from 'node:module';import { availableParallelism } from 'node:os';import { join } from 'node:path';import { machineHome } from './machine-home.js';+import { Refused } from './refused.js';++const asyncOffers = new WeakMap();+const independentChildren = new WeakMap();+let activeAsyncWait = null;+let ownsFileToken = false;/** Names the pool a test-file process takes from, and the file process that started this run, as JSON. */export const TEST_FILE_POOL_ENV = 'PULLBOARD_TEST_FILE_POOL';@@ -210,6 +218,7 @@ export async function takeTestFileToken(env = process.env) {const db = await openPool(pool.home);immediate(db, () => db.prepare('INSERT OR IGNORE INTO file_waiter(pid) VALUES (?)').run(process.pid));let pruned = 0;+ let reported = false;let path;while (true) {const { taken, ahead } = standing(db);@@ -219,6 +228,11 @@ export async function takeTestFileToken(env = process.env) {path = admit(db, pool.cores, pool.lender, pool.call);if (path !== false) break;}+ if (!reported && pool.call?.startsWith('async:') && pool.lender &&+ db.prepare('SELECT 1 FROM file_holder h WHERE h.pid = ? AND NOT EXISTS (SELECT 1 FROM file_call WHERE lender = h.pid)').get(pool.lender)) {+ process.stderr.write(`test-file-pool: parent ${pool.lender} is holding its token while nested files wait; use awaitNestedRun(child) only while yielding.\n`);+ reported = true;+ }await new Promise(done => setTimeout(done, POLL_MS));}process.once('exit', () => {@@ -226,6 +240,8 @@ export async function takeTestFileToken(env = process.env) {catch { /* A row left behind is pruned once this process is gone. */ }});env[TEST_FILE_POOL_ENV] = JSON.stringify({ home: pool.home, cores: pool.cores });+ ownsFileToken = true;+ lendThroughAsyncSpawn(pool, env, db, path);lendThroughSyncCalls(pool, env, db, path);return Date.now() - asked;}@@ -273,6 +289,124 @@ function lendThroughSyncCalls(pool, env, db, path) {syncBuiltinESMExports();}+/** Close a loan before draining its borrowed descent, so no new file can race the last sample. */+async function closeAsyncCall(db, call, callPath, closed) {+ db.prepare('UPDATE file_call SET closing = 1 WHERE call = ?').run(call);+ await closed;+ const descent = db.prepare("SELECT pid FROM file_holder WHERE path = ? OR substr(path, 1, ?) = ?");+ while (descent.all(callPath, callPath.length + 1, `${callPath}/`).some(({ pid }) => alive(pid))) {+ await new Promise(next => setTimeout(next, POLL_MS));+ }+ db.prepare('DELETE FROM file_call WHERE call = ?').run(call);+}++/** Observe close from spawn onward without consuming an otherwise unhandled child error. */+function observeAsyncChild(child) {+ const outcome = { error: null, status: null, signal: null };+ child.once(errorMonitor, error => { outcome.error = error; });+ const closed = new Promise(resolve => child.once('close', (status, signal) => {+ outcome.status = status;+ outcome.signal = signal;+ resolve(outcome);+ }));+ return { outcome, closed };+}++/** Await a raw child through close, preserving a spawn error instead of inventing an exit status. */+async function rawChildResult(observed, child) {+ const onError = () => {};+ child.once('error', onError);+ try {+ const result = await observed.closed;+ if (result.error) throw result.error;+ return { status: result.status, signal: result.signal };+ } finally { child.removeListener('error', onError); }+}++/**+ * Explicitly await a nested child while promising that this test file yields its token until the wait returns.+ * Pass a ChildProcess or the original fixture promise carrying `.child`; fixture results/errors are unchanged.+ * This is a caller contract, not proof that arbitrary callbacks stop computing: do no unrelated work and never+ * abandon the returned wait through Promise.race. Signal the child inside the wait, then let this helper drain.+ * Only one explicit wait may be active in a file. Plain spawned children borrow nothing, and isolated child pools+ * retain ordinary waits. Standalone fixture promises also retain normal waits; an unobserved raw child outside+ * an admitted file is refused because past error/close events cannot be reconstructed. Closing admission before finally draining borrowed descendants prevents an early return.+ * If cleanup cannot prove the token is safe to resume, this test process exits rather than returning a live loan.+ */+export async function awaitNestedRun(handle) {+ const child = handle?.child ?? handle;+ const isChild = child && typeof child.once === 'function' && typeof child.kill === 'function';+ if (!isChild && ownsFileToken) throw new Refused('NESTED_RUN_HANDLE_REQUIRED', 'Pass the original child or fixture promise with .child to awaitNestedRun.');+ if (!ownsFileToken && typeof handle?.then === 'function') return await handle;+ const offer = isChild ? asyncOffers.get(child) : null;+ if (!offer && isChild && !independentChildren.has(child)) throw new Refused('NESTED_RUN_OFFER_REQUIRED', 'Start this child with the current spawn export after token admission, then pass its original handle.');+ if (!offer) {+ if (isChild && typeof handle?.then !== 'function') {+ const observed = independentChildren.get(child);+ return rawChildResult(observed, child);+ }+ return await handle;+ }+ if (offer.used) throw new Refused('NESTED_RUN_WAIT_REUSED', 'This child was already awaited through its loan. Await the original returned wait instead.');+ if (activeAsyncWait) throw new Refused('NESTED_RUN_WAIT_ACTIVE', 'This file already lends its token. Finish that wait before lending to another child.');+ offer.used = true;+ activeAsyncWait = offer.call;+ const { db, call, path } = offer;+ let opened = false;+ // The explicit wait owns spawn-error handling; the dormant observer alone never swallows it.+ const onError = () => {};+ child.once('error', onError);+ try {+ immediate(db, () => db.prepare('INSERT INTO file_call(call, lender, path) VALUES (?, ?, ?)').run(call, process.pid, path));+ opened = true;+ return typeof handle?.then === 'function' ? await handle : await rawChildResult(offer, child);+ } finally {+ try { if (opened) await closeAsyncCall(db, call, path, offer.closed); }+ catch (error) {+ process.stderr.write(`test-file-pool: cannot close the nested loan safely (${error.code ?? 'UNKNOWN'}); exiting this test process.\n`);+ process.exit(1);+ }+ finally { child.removeListener('error', onError); activeAsyncWait = null; }+ }+}++/**+ * Give an async child an exact dormant offer before its environment is copied. An offer creates no loan row:+ * until awaitNestedRun explicitly activates it, admission counts the parent and child independently. A child+ * already admitted before activation keeps its own token; only later exact-call admissions borrow the place.+ * Preserve prior spawn guards, options and events; a fixture that chooses another pool gets no offer.+ */+function lendThroughAsyncSpawn(pool, env, db, path) {+ const ours = env[TEST_FILE_POOL_ENV];+ const original = childProcess.spawn;+ childProcess.spawn = function offeredAsyncSpawn(...args) {+ const second = args[1];+ // Leave invalid signatures to Node, and retain a third options object when args is null or omitted.+ if (second != null && !Array.isArray(second) && typeof second !== 'object') return original.apply(this, args);+ const optionsAt = second == null || Array.isArray(second) ? 2 : 1;+ const options = args[optionsAt];+ if (options !== undefined && (options === null || typeof options !== 'object' || Array.isArray(options))) return original.apply(this, args);+ // Match Node's own option projection and its enumerable environment, including prototype values.+ const normalized = { __proto__: null, ...options };+ const childEnv = normalized.env || process.env;+ const projected = Object.create(null);+ for (const name in childEnv) projected[name] = childEnv[name];+ args[optionsAt] = { __proto__: null, ...normalized, env: projected };+ if (projected[TEST_FILE_POOL_ENV] !== ours) {+ const independent = original.apply(this, args);+ independentChildren.set(independent, observeAsyncChild(independent));+ return independent;+ }+ const call = `async:${randomUUID()}`;+ const lent = JSON.stringify({ home: pool.home, cores: pool.cores, lender: process.pid, call });+ projected[TEST_FILE_POOL_ENV] = lent;+ const child = original.apply(this, args);+ asyncOffers.set(child, { db, call, path: `${path}/${call}`, used: false, ...observeAsyncChild(child) });+ return child;+ };+ syncBuiltinESMExports();+}+/*** Order test files longest-first by their last recorded wall time, so the slowest file never starts last.* A file with no record keeps its place after the timed ones; ties keep the given order.diff --git a/test/async-run-callers.md b/test/async-run-callers.mdnew file mode 100644index 00000000..5bbb17fb--- /dev/null+++ b/test/async-run-callers.md@@ -0,0 +1,40 @@+# Asynchronous nested test runs++Item #1107 adds `awaitNestedRun(child)`. Its caller promises to yield until the returned wait settles. This is a scheduling contract, not proof that other JavaScript callbacks stop computing. Do not abandon the wait with `Promise.race`, do unrelated work while it is active, or open another loan in the same file. A timeout must signal its owned child inside the wait and let close and borrowed-descendant cleanup finish before returning.++Pass the original fixture promise with its `.child`, a raw child from the admitted process's current `spawn` export, or a completion promise explicitly retaining that same child. The original completion value and error are preserved. A standalone fixture promise is an ordinary wait. An unobserved standalone raw child is refused: past error and close events cannot be reconstructed. A deliberately independent child pool retains ordinary token accounting. An `exec`, `execFile`, `fork` or previously captured spawn handle with no exact offer is refused. The spawn wrapper preserves effective Node option/environment fields, including inherited environment values; it does not promise original option-object identity. Seventeen synthetic argument/environment cases compare against a separate Node process that loads neither loan wrapper.++A spawn only carries a dormant per-child offer. It does not create a loan. Explicit waiting activates the offer; an already admitted ordinary child keeps its own token. The helper closes new admission before draining the borrowed path. If cleanup cannot establish safe resumption, the owning test process exits instead of returning a live loan.++## Terminal waits migrated++| Caller | Wait and pool behavior |+| --- | --- |+| `test/runner-pid.test.js` | Both the outer runner and generated nested runner use the helper. Existing runner-PID observations and exit-code assertions remain. |+| `test/test-isolation.test.js` | The original fixture promises for calm and hostile-machine runner probes use the helper. Isolation inputs and assertions remain. The direct Node negative control keeps the inherited pool and also uses the explicit helper; it does not become a production-runner invocation. |+| `test/view-port.test.js` | The occupied-port nested suite uses the helper around its original promise. The unrelated port listener remains running. |+| `test/resources.test.js` | `runWaiter` uses the helper for the short-lock and long-lock terminal runner waits. The lock-holder process is not lent to. |+| `test/gate-admission.test.js` | Outer private-fixture runner waits use explicit helper pass-through. The parallel outer runs have deliberately separate pools. The generated busy parent deliberately does not lend. New one-token progress and no-helper diagnostic controls distinguish the two contracts. |+| `test/runner-browser-free-fixture.js` | Runner and gate completion waits use the helper while preserving the original hold/free order: the initial remote run intentionally keeps the local slot held, and local fallback waits begin after release. The fixture deliberately removes inherited test-pool state, so these are ordinary independent-pool waits. |+| `test/runner-tooling-fixture.js` | `awaitRoundTrip` keeps its exact child on a terminal progress-monitor promise. Its existing phase deadlines stop the owned group inside the wait; helper cleanup completes before return or throw. This covers `runThroughGate` and callers of the shared monitor. |+| `test/runners.test.js` | Terminal registered-runner checks use the migrated shared `awaitRoundTrip` / `runThroughGate` seam. The file's other arbitrary process starts are not all runner starts. |+| `test/runner-paired-rerun-fixture.js` | Its actual paired-rerun gate uses the shared terminal monitor. Separate phase-emitter and CPU-worker children do not become runner invocations merely because this file also configures a runner. |+| `test/gate-profile.test.js` | After releasing the queue holder, both the two-run gate and submission terminal deadlines are inside the helper. A timeout stops and awaits the owned child before returning its error. Existing output/profile results are preserved. |+| `test/landing-shards.test.js` | Single landing and runner-answer waits carry their exact child through deadline cancellation and final helper drain. The concurrent-pair case still starts both landings immediately; only lending is serial, and both terminal results settle before an error is surfaced. |++## Interactive phases reserved for #1152++These callers coordinate with a running nested test before its final close. Lending only at their final close does not fix an earlier marker wait; lending at spawn would violate the explicit yielding contract. They are not represented as deadlock-free by #1107.++| Caller | Outstanding phase |+| --- | --- |+| `test/resources.test.js` | The non-browser check/submit admission cases wait for an item/submit marker or queue observation, inspect other leases, then release a barrier before the terminal result. |+| `test/gate-resource.test.js` | `launchTestRunner`, whole-suite holders and focused-run probes wait for file-written markers and gate/resource assertions before release. Group completion must preserve these phases and each child's original result shape. |+| `test/run-tests.test.js` | Worker identity, descendant-drain and focused-pool cases inspect readiness, capture identities and release barriers before terminal close. Their existing timeout races must not abandon a live loan. |+| `test/cockpit/stable.test.js` | Runner-victim cases intentionally observe browser ownership, kill the known victim and prove drain. This is an interactive custody test, not a normal successful terminal wait. It belongs to the view lane. |++## Exclusions and scope of the inventory++The `land.test.js` adoption children use a custom landing-gate script; the actual production-runner gate in that area is invoked synchronously. `verdict-check.test.js`'s relevant verifier check is `true`. The separately inspected resource-verification fixtures use an empty check or `printf`. Browser launches, long-lived servers, classifier source strings, CPU workers and process-custody descendants are not counted as asynchronous runner starts without an execution edge.++This inventory follows actual direct runner starts and the configured CLI/gate/shard/monitor edges in the current test source. It supersedes the item's old unsupported reference to exactly 18 files; it does not claim that arbitrary dynamically constructed JavaScript can be exhaustively classified by a text search. Item #1152 owns the named interactive gaps. No promise here guarantees that a caller violating the yielding contract remains idle.diff --git a/test/fixture-child.js b/test/fixture-child.jsindex 203d0f11..87c19059 100644--- a/test/fixture-child.js+++ b/test/fixture-child.js@@ -1,6 +1,7 @@/** Shared private fixture child runner and redacted failure diagnostics [C7]. */import { spawn, spawnSync } from 'node:child_process';import { performance } from 'node:perf_hooks';+export { awaitNestedRun } from '../src/test-file-pool.js';const SENSITIVE_NAME = /(?:token|secret|password|private.?key|access.?key|relay[_ -]?key|pairing.?code|verification.?code)/iu;const activeFixtureChildren = new Set();diff --git a/test/gate-admission.test.js b/test/gate-admission.test.jsindex b65604f7..62d796f2 100644--- a/test/gate-admission.test.js+++ b/test/gate-admission.test.js@@ -1,6 +1,7 @@/** Test files on one machine never outnumber its cores, and the longest files start first [C7]. */+import { awaitNestedRun } from './fixture-child.js';import assert from 'node:assert/strict';-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { fileURLToPath } from 'node:url';@@ -40,7 +41,7 @@ for (const [name, command] of ${JSON.stringify(commands)}) {process.stdout.write(JSON.stringify(decisions));`;// Only this private machine fixture drops the outer proof's admission markers.for (const key of [GATE_SLOT_HELD_ENV, GATE_SLOT_POOL_ENV, GATE_SLOT_TOKEN_ENV, BROWSER_SLOT_HELD_ENV]) delete env[key];- const result = await runFixtureChildAsync(process.execPath, ['--input-type=module', '-e', source], { cwd: root, env });+ const result = await awaitNestedRun(runFixtureChildAsync(process.execPath, ['--input-type=module', '-e', source], { cwd: root, env }));assert.equal(result.status, 0, result.failure ?? result.stderr);const decisions = JSON.parse(result.stdout);for (const [index, [name, , expected]] of commands.entries()) {@@ -80,7 +81,7 @@ const decisions = [];for (const [command] of ${JSON.stringify(commands)}) decisions.push(await checkNeedsBrowser(process.cwd(), command));const short = await explicitCheckFiles(process.cwd(), ${JSON.stringify(core)});process.stdout.write(JSON.stringify({ decisions, short }));`;- const result = await runFixtureChildAsync(process.execPath, ['--input-type=module', '-e', source], { cwd: root, env });+ const result = await awaitNestedRun(runFixtureChildAsync(process.execPath, ['--input-type=module', '-e', source], { cwd: root, env }));assert.equal(result.status, 0, result.failure ?? result.stderr);const actual = JSON.parse(result.stdout);assert.deepEqual(actual.decisions, commands.map(([, browser]) => browser));@@ -132,8 +133,8 @@ test('four runs never hold more test files than cores, and the longest-recordedconst { root, env, log } = fixture(t, 4);const files = ['a.test.js', 'b.test.js', 'c.test.js', 'd.test.js', 'e.test.js', 'z-slow.test.js'];for (const file of files) writeFileSync(join(root, file), timedFile(file, 300));- const runs = await Promise.all([1, 2, 3, 4].map(run => runFixtureChildAsync(process.execPath, [runner, ...files],- { cwd: root, env: { ...env, FIXTURE_RUN: String(run) } })));+ const runs = await Promise.all([1, 2, 3, 4].map(run => awaitNestedRun(runFixtureChildAsync(process.execPath, [runner, ...files],+ { cwd: root, env: { ...env, FIXTURE_RUN: String(run) } }))));for (const result of runs) assert.equal(result.status, 0, `${result.failure ?? ""}\n${result.stdout.slice(-3000)}`);const events = log();assert.equal(events.filter(event => event.at === 'start').length, 24, 'every file of every run ran');@@ -161,7 +162,7 @@ test('a file waiting on a nested run lends its place, so saturated parents stillfor (const file of ['outer-a.test.js', 'outer-b.test.js']) {writeFileSync(join(root, file), timedFile(file, 0, nested).replace("mark('start');", '').replace("mark('end');", ''));}- const result = await runFixtureChildAsync(process.execPath, [runner, 'outer-a.test.js', 'outer-b.test.js'], { cwd: root, env: { ...env, FIXTURE_RUN: 'outer' } });+ const result = await awaitNestedRun(runFixtureChildAsync(process.execPath, [runner, 'outer-a.test.js', 'outer-b.test.js'], { cwd: root, env: { ...env, FIXTURE_RUN: 'outer' } }));assert.equal(result.status, 0, result.failure ?? result.stdout);const events = log();assert.equal(events.filter(event => event.at === 'start').length, 4, 'both inner files ran under both outer files');@@ -213,13 +214,245 @@ test('busy parent', async () => {}});`);- const result = await runFixtureChildAsync(process.execPath, [runner, 'busy.test.js'], { cwd: root, env: { ...env, FIXTURE_RUN: 'outer' } });+ const result = await awaitNestedRun(runFixtureChildAsync(process.execPath, [runner, 'busy.test.js'], { cwd: root, env: { ...env, FIXTURE_RUN: 'outer' } }));assert.equal(result.status, 0, result.failure ?? result.stdout);const events = log();assert.equal(events.filter(event => event.at === 'start').length, 2, 'both nested files ran');assert.equal(peak(events), 1, 'with the busy parent holding one of 2 places, its nested files share the one left');});+test('an async parent lends its token through awaitNestedRun [C7]', async (t) => {+ const poolModule = new URL('../src/test-file-pool.js', import.meta.url).href;+ const api = await import(poolModule);+ assert.equal(typeof api.awaitNestedRun, 'function', 'an explicit yielding-wait helper is available');+ const { root, env, log } = fixture(t, 1);+ writeFileSync(join(root, 'inner.test.js'), timedFile('inner.test.js', 0));+ writeFileSync(join(root, 'parent.test.js'), `import assert from 'node:assert/strict';+import { spawn } from 'node:child_process';+import { test } from 'node:test';+import { awaitNestedRun } from ${JSON.stringify(poolModule)};+test('yielding parent', async () => {+ const child = spawn(process.execPath, [${JSON.stringify(runner)}, 'inner.test.js'], { cwd: ${JSON.stringify(root)}, env: { ...process.env, FIXTURE_RUN: 'inner' }, stdio: ['ignore', 'pipe', 'pipe'] });+ child.stdout.resume();+ child.stderr.resume();+ const result = await awaitNestedRun(child);+ assert.equal(result.status, 0);+ assert.equal(result.signal, null);+});+`);+ const result = await awaitNestedRun(runFixtureChildAsync(process.execPath, [runner, 'parent.test.js'], { cwd: root, env: { ...env, FIXTURE_RUN: 'outer' } }));+ assert.equal(result.status, 0, result.failure ?? result.stdout);+ assert.equal(log().filter(event => event.at === 'start').length, 1, 'the nested file ran despite a one-token pool');+ assert.equal(await occupiedPlaces(env.PULLBOARD_MACHINE_HOME), 0, 'no holder remains after the parent exits');+ const db = new DatabaseSync(join(env.PULLBOARD_MACHINE_HOME, 'test-file-pool.sqlite'));+ try { assert.equal(db.prepare('SELECT count(*) AS n FROM file_call').get().n, 0, 'the explicit loan drained and closed'); }+ finally { db.close(); }++ const blocked = fixture(t, 1);+ writeFileSync(join(blocked.root, 'inner.test.js'), timedFile('inner.test.js', 0));+ writeFileSync(join(blocked.root, 'parent.test.js'), `import assert from 'node:assert/strict';+import { spawn } from 'node:child_process';+import { DatabaseSync } from 'node:sqlite';+import { join } from 'node:path';+import { test } from 'node:test';+test('parent without the explicit wait', { timeout: 10_000 }, async (t) => {+ const child = spawn(process.execPath, [${JSON.stringify(runner)}, 'inner.test.js'], { cwd: ${JSON.stringify(blocked.root)}, env: process.env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });+ let live = true;+ t.after(() => { if (live) { try { process.kill(-child.pid, 'SIGKILL'); } catch (error) { if (error.code !== 'ESRCH') throw error; } } });+ let text = '';+ const closed = new Promise(resolve => child.once('close', code => { live = false; resolve(code); }));+ await new Promise(resolve => {+ const sample = chunk => { text += chunk; if (text.includes('holding its token while nested files wait')) resolve(); };+ child.stdout.on('data', sample); child.stderr.on('data', sample);+ });+ const home = JSON.parse(process.env.PULLBOARD_TEST_FILE_POOL).home;+ const db = new DatabaseSync(join(home, 'test-file-pool.sqlite'), { readOnly: true });+ try {+ assert.equal(db.prepare('SELECT count(*) AS n FROM file_holder WHERE pid = ?').get(process.pid).n, 1);+ assert.ok(db.prepare('SELECT count(*) AS n FROM file_waiter').get().n > 0);+ assert.equal(db.prepare('SELECT count(*) AS n FROM file_call').get().n, 0);+ } finally { db.close(); }+ assert.ok(text.includes('use awaitNestedRun(child) only while yielding'));+ process.kill(-child.pid, 'SIGTERM');+ await closed;+});+`);+ const noLoan = await awaitNestedRun(runFixtureChildAsync(process.execPath, [runner, 'parent.test.js'], { cwd: blocked.root, env: blocked.env }));+ assert.equal(noLoan.status, 0, `${noLoan.failure ?? ''}\n${noLoan.stdout}`);+ assert.equal(await occupiedPlaces(blocked.env.PULLBOARD_MACHINE_HOME), 0, 'the bounded negative control cleaned its real processes');+});++test('an explicit async loan refuses duplicate and concurrent waits and preserves child failures [C7]', async (t) => {+ const { root, env } = fixture(t, 1);+ const poolModule = new URL('../src/test-file-pool.js', import.meta.url).href;+ writeFileSync(join(root, 'inner.test.js'), timedFile('inner.test.js', 0));+ writeFileSync(join(root, 'parent.test.js'), `import assert from 'node:assert/strict';+import { spawn } from 'node:child_process';+import { test } from 'node:test';+import { awaitNestedRun } from ${JSON.stringify(poolModule)};+test('explicit wait contracts', { timeout: 10_000 }, async (t) => {+ const start = () => {+ const child = spawn(process.execPath, [${JSON.stringify(runner)}, 'inner.test.js'], { cwd: ${JSON.stringify(root)}, stdio: ['ignore', 'pipe', 'pipe'] });+ child.stdout.resume(); child.stderr.resume();+ return child;+ };+ const first = start();+ const waiting = awaitNestedRun(first);+ await assert.rejects(awaitNestedRun(first), { code: 'NESTED_RUN_WAIT_REUSED' });+ const second = start();+ await assert.rejects(awaitNestedRun(second), { code: 'NESTED_RUN_WAIT_ACTIVE' });+ assert.equal((await waiting).status, 0);+ assert.equal((await awaitNestedRun(second)).status, 0);+ const missing = spawn(${JSON.stringify(join(root, 'missing-child'))}, [], { stdio: 'ignore' });+ await assert.rejects(awaitNestedRun(missing), { code: 'ENOENT' });+ const failed = spawn(process.execPath, ['-e', 'process.exit(7)'], { stdio: 'ignore' });+ assert.deepEqual(await awaitNestedRun(failed), { status: 7, signal: null });+ const late = spawn(${JSON.stringify(join(root, 'missing-late-child'))}, [], { stdio: 'ignore' });+ const seen = new Promise(resolve => { late.on('error', () => {}); late.once('close', resolve); });+ await seen;+ await assert.rejects(awaitNestedRun(late), { code: 'ENOENT' });+ const separate = { ...process.env };+ delete separate.PULLBOARD_TEST_FILE_POOL;+ const independent = spawn(${JSON.stringify(join(root, 'missing-independent-child'))}, [], { env: separate, stdio: 'ignore' });+ await assert.rejects(awaitNestedRun(independent), { code: 'ENOENT' });+ const fallback = spawn(process.execPath, [${JSON.stringify(runner)}, 'inner.test.js'], { env: false, detached: true, stdio: 'ignore' });+ let live = true;+ fallback.once('close', () => { live = false; });+ t.after(() => { if (live) { try { process.kill(-fallback.pid, 'SIGKILL'); } catch (error) { if (error.code !== 'ESRCH') throw error; } } });+ assert.equal((await awaitNestedRun(fallback)).status, 0, 'a native falsy-env fallback still borrows in a one-token pool');+});+`);+ const result = await awaitNestedRun(runFixtureChildAsync(process.execPath, [runner, 'parent.test.js'], { cwd: root, env }));+ assert.equal(result.status, 0, result.failure ?? result.stdout);+ assert.equal(await occupiedPlaces(env.PULLBOARD_MACHINE_HOME), 0);+});++test('async offers preserve spawn argument overloads and Node validation [C7]', async (t) => {+ const { root, env } = fixture(t, 1);+ const poolModule = new URL('../src/test-file-pool.js', import.meta.url).href;+ const probe = join(root, 'options.sh');+ const marker = join(root, 'options-output');+ writeFileSync(probe, String.raw`#!/bin/sh+printf '%s\n' "$ASYNC_OFFER_MODE" > "$ASYNC_OFFER_DEST"+`);+ chmodSync(probe, 0o755);+ writeFileSync(join(root, 'spawn-cases.mjs'), `import { existsSync, readFileSync, rmSync } from 'node:fs';+const probe = ${JSON.stringify(probe)};+const marker = ${JSON.stringify(marker)};+export const variants = ['undefined-args', 'null-args', 'object-options', 'array-args', 'invalid-args', 'invalid-options', 'null-array-options', 'null-undefined-options', 'null-null-options', 'inherited-env', 'inherited-options', 'false-env', 'zero-env', 'empty-env', 'separate-env', 'own-env-getter', 'separate-env-getter'];+export function startVariant(start, variant) {+ rmSync(marker, { force: true });+ process.env.ASYNC_OFFER_MODE = 'fallback';+ process.env.ASYNC_OFFER_DEST = marker;+ const options = { cwd: ${JSON.stringify(root)}, env: { ...process.env, ASYNC_OFFER_MODE: 'retained-options' }, stdio: 'ignore' };+ if (variant === 'undefined-args') return start(probe, undefined, options);+ if (variant === 'null-args') return start(probe, null, options);+ if (variant === 'object-options') return start(probe, options);+ if (variant === 'array-args') return start(probe, [], options);+ if (variant === 'invalid-args') return start(probe, 'invalid args');+ if (variant === 'invalid-options') return start(probe, [], 'invalid options');+ if (variant === 'null-array-options') return start(probe, [], null);+ if (variant === 'null-undefined-options') return start(probe, undefined, null);+ if (variant === 'null-null-options') return start(probe, null, null);+ if (variant === 'inherited-env') {+ options.env = Object.assign(Object.create({ ASYNC_OFFER_MODE: 'inherited-value' }), {+ PULLBOARD_TEST_FILE_POOL: process.env.PULLBOARD_TEST_FILE_POOL, ASYNC_OFFER_DEST: marker,+ });+ } else if (variant === 'inherited-options') {+ return start(probe, Object.assign(Object.create({ env: { ASYNC_OFFER_MODE: 'ignored' }, cwd: '/missing/inherited-spawn-option' }), { stdio: 'ignore' }));+ } else if (variant === 'false-env') options.env = false;+ else if (variant === 'zero-env') options.env = 0;+ else if (variant === 'empty-env') options.env = '';+ else if (variant === 'separate-env') options.env.PULLBOARD_TEST_FILE_POOL = 'separate-fixture-pool';+ else if (variant === 'own-env-getter' || variant === 'separate-env-getter') {+ let reads = 0;+ Object.defineProperty(options, 'env', { enumerable: true, get() {+ reads++;+ return { ...process.env, ASYNC_OFFER_MODE: 'getter-' + reads,+ ...(variant === 'separate-env-getter' ? { PULLBOARD_TEST_FILE_POOL: 'separate-fixture-pool' } : {}) };+ } });+ }+ return start(probe, [], options);+}+export function observation(result) {+ return { status: result.status, signal: result.signal, mode: existsSync(marker) ? readFileSync(marker, 'utf8').trim() : null };+}+`);+ const oracle = join(root, 'native-oracle.mjs');+ writeFileSync(oracle, `import { spawnSync } from 'node:child_process';+import { variants, startVariant, observation } from './spawn-cases.mjs';+const records = variants.map(variant => {+ try { return { variant, observed: observation(startVariant(spawnSync, variant)) }; }+ catch (error) { return { variant, observed: { error: error.code } }; }+});+process.stdout.write(JSON.stringify(records));+`);+ // This private non-test oracle loads no runner/preload, so its primitive is independent of both loan wrappers.+ const oracleEnv = { ...env, NODE_OPTIONS: '' };+ delete oracleEnv.NODE_TEST_CONTEXT;+ const native = runFixtureChild(process.execPath, [oracle], { cwd: root, env: oracleEnv, encoding: 'utf8' });+ assert.equal(native.status, 0, native.failure ?? native.stderr);+ const expected = JSON.parse(native.stdout);+ t.diagnostic('independent Node spawn observations: ' + JSON.stringify(expected));+ writeFileSync(join(root, 'expected.json'), JSON.stringify(expected));+ writeFileSync(join(root, 'parent.test.js'), `import assert from 'node:assert/strict';+import { spawn } from 'node:child_process';+import { readFileSync } from 'node:fs';+import { test } from 'node:test';+import { awaitNestedRun } from ${JSON.stringify(poolModule)};+import { variants, startVariant, observation } from './spawn-cases.mjs';+test('offered spawn matches independently loaded Node', async () => {+ const expected = JSON.parse(readFileSync('expected.json', 'utf8'));+ for (const variant of variants) {+ let observed;+ try { observed = observation(await awaitNestedRun(startVariant(spawn, variant))); }+ catch (error) { observed = { error: error.code }; }+ assert.deepEqual(observed, expected.find(record => record.variant === variant).observed, variant);+ }+});+`);+ const result = await awaitNestedRun(runFixtureChildAsync(process.execPath, [runner, 'parent.test.js'], { cwd: root, env }));+ assert.equal(result.status, 0, `${result.failure ?? ''}\n${result.stdout}`);+ assert.equal(await occupiedPlaces(env.PULLBOARD_MACHINE_HOME), 0);+});++test('an async loan whose cleanup fails exits without resuming its parent [C7]', async (t) => {+ const { root, env } = fixture(t, 1);+ const poolModule = new URL('../src/test-file-pool.js', import.meta.url).href;+ writeFileSync(join(root, 'inner.test.js'), `import { existsSync, writeFileSync } from 'node:fs';+import { test } from 'node:test';+test('borrowed child', async () => {+ writeFileSync('inner-ready', 'ready');+ while (!existsSync('release-inner')) await new Promise(next => setTimeout(next, 10));+});+`);+ writeFileSync(join(root, 'parent.test.js'), `import { spawn } from 'node:child_process';+import { existsSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { DatabaseSync } from 'node:sqlite';+import { test } from 'node:test';+import { awaitNestedRun } from ${JSON.stringify(poolModule)};+test('a broken private pool must not return a live loan', async () => {+ const child = spawn(process.execPath, [${JSON.stringify(runner)}, 'inner.test.js'], { stdio: ['ignore', 'pipe', 'pipe'] });+ child.stdout.resume(); child.stderr.resume();+ const waiting = awaitNestedRun(child);+ while (!existsSync('inner-ready')) await new Promise(next => setTimeout(next, 10));+ const home = JSON.parse(process.env.PULLBOARD_TEST_FILE_POOL).home;+ const db = new DatabaseSync(join(home, 'test-file-pool.sqlite'));+ db.exec('DROP TABLE file_call');+ db.close();+ writeFileSync('release-inner', 'release');+ try { await waiting; } catch { writeFileSync('parent-resumed', 'caught'); }+ writeFileSync('parent-resumed', 'returned');+});+`);+ const result = await awaitNestedRun(runFixtureChildAsync(process.execPath, [runner, 'parent.test.js'], { cwd: root, env }));+ assert.equal(result.status, 1, `${result.failure ?? ''}\n${result.stdout}`);+ assert.match(result.stdout + result.stderr, /cannot close the nested loan safely/);+ assert.equal(existsSync(join(root, 'parent-resumed')), false, 'neither return nor catch resumed the parent');+ assert.equal(await occupiedPlaces(env.PULLBOARD_MACHINE_HOME), 0);+});+test('a run a synchronous call leaves behind lends nothing once the call returns [C7]', async (t) => {const { root, env, log } = fixture(t, 1);for (const file of ['inner-a.test.js', 'inner-b.test.js']) writeFileSync(join(root, file), timedFile(file, 200));@@ -229,7 +462,7 @@ test('a run a synchronous call leaves behind lends nothing once the call returnsconst until = Date.now() + 1500;while (Date.now() < until) { /* computing in its own place */ }`;writeFileSync(join(root, 'parent.test.js'), timedFile('parent.test.js', 0, detached));- const result = await runFixtureChildAsync(process.execPath, [runner, 'parent.test.js'], { cwd: root, env: { ...env, FIXTURE_RUN: 'outer' } });+ const result = await awaitNestedRun(runFixtureChildAsync(process.execPath, [runner, 'parent.test.js'], { cwd: root, env: { ...env, FIXTURE_RUN: 'outer' } }));assert.equal(result.status, 0, result.failure ?? result.stdout);const deadline = Date.now() + 30_000;while (log().filter(event => event.run === 'inner' && event.at === 'end').length < 2 && Date.now() < deadline) await new Promise(next => setTimeout(next, 100));@@ -249,7 +482,7 @@ test('a synchronous call returns only after the file it lent its place to has exexecSync(${JSON.stringify(`${JSON.stringify(process.execPath)} ${JSON.stringify(runner)} inner.test.js > /dev/null 2>&1 & ${started}`)}, { cwd: ${JSON.stringify(root)}, env: { ...process.env, FIXTURE_RUN: 'inner' } });mark('resume');`;writeFileSync(join(root, 'parent.test.js'), timedFile('parent.test.js', 0, lingering));- const result = await runFixtureChildAsync(process.execPath, [runner, 'parent.test.js'], { cwd: root, env: { ...env, FIXTURE_RUN: 'outer' } });+ const result = await awaitNestedRun(runFixtureChildAsync(process.execPath, [runner, 'parent.test.js'], { cwd: root, env: { ...env, FIXTURE_RUN: 'outer' } }));assert.equal(result.status, 0, result.failure ?? result.stdout);const deadline = Date.now() + 30_000;while (!log().some(event => event.file === 'inner.test.js' && event.at === 'end') && Date.now() < deadline) await new Promise(next => setTimeout(next, 100));@@ -274,7 +507,7 @@ test('c', () => { execSync(${JSON.stringify(startD)}, { cwd: ${JSON.stringify(rocatch { /* C was killed, so its run fails; P only resumes. */ }mark('resume');`;writeFileSync(join(root, 'p.test.js'), timedFile('p.test.js', 0, runC));- const result = await runFixtureChildAsync(process.execPath, [runner, 'p.test.js'], { cwd: root, env: { ...env, FIXTURE_RUN: 'p' } });+ const result = await awaitNestedRun(runFixtureChildAsync(process.execPath, [runner, 'p.test.js'], { cwd: root, env: { ...env, FIXTURE_RUN: 'p' } }));assert.equal(result.status, 0, `${result.failure ?? ''}\n${result.stdout.slice(-3000)}`);const deadline = Date.now() + 30_000;while (!log().some(event => event.file === 'd.test.js' && event.at === 'end') && Date.now() < deadline) await new Promise(next => setTimeout(next, 100));diff --git a/test/gate-profile.test.js b/test/gate-profile.test.jsindex f9f3b574..2d8f0abf 100644--- a/test/gate-profile.test.js+++ b/test/gate-profile.test.js@@ -1,4 +1,5 @@/** Real gate, item-check and verifier profiles parse emitted timings [C7,V10]. */+import { awaitNestedRun } from './fixture-child.js';import assert from 'node:assert/strict';import { execFileSync, spawn, spawnSync } from 'node:child_process';import { once } from 'node:events';@@ -160,7 +161,15 @@ test('a timing profile records two runner invocations and the real gate-slot waigateTimer = setTimeout(() => reject(new Error('private gate did not finish within 60 seconds')), 60_000); // budget: hang ceiling for private gate completion; no throughput claim.});let status;- try { [status] = await Promise.race([gateExited, timeout]); }+ try {+ const terminal = Promise.race([gateExited, timeout]).catch(async error => {+ if (gate.exitCode === null && gate.signalCode === null) gate.kill('SIGTERM');+ await gateExited;+ throw error;+ });+ terminal.child = gate;+ [status] = await awaitNestedRun(terminal);+ }finally { clearTimeout(gateTimer); }result = { status, stdout: Buffer.concat(gateOutput).toString('utf8'), stderr: '' };} finally {@@ -353,6 +362,7 @@ function startProfiledSubmit(box, cwd) {const finished = new Promise(resolveFinished => child.once('close', (code, signal) => resolveFinished({code, signal, stdout: Buffer.concat(stdout).toString('utf8'), stderr: Buffer.concat(stderr).toString('utf8'),})));+ finished.child = child;return { child, finished };}@@ -404,10 +414,16 @@ async function runProfileSubmission(box, queue) {}let timer;try {- result = await Promise.race([+ const terminal = Promise.race([submit.finished,new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('private profile submit exceeded 60 seconds')), 60_000); }), // budget: hang ceiling for private submission completion; no throughput claim.- ]);+ ]).catch(async error => {+ if (submit.child.exitCode === null && submit.child.signalCode === null) submit.child.kill('SIGTERM');+ await submit.finished;+ throw error;+ });+ terminal.child = submit.child;+ result = await awaitNestedRun(terminal);} finally {clearTimeout(timer);}diff --git a/test/landing-shards.test.js b/test/landing-shards.test.jsindex 3f9f4666..20569eb5 100644--- a/test/landing-shards.test.js+++ b/test/landing-shards.test.js@@ -1,4 +1,5 @@/** The landing gate splits its test files into shards across local slots and runners [C7,V4]. */+import { awaitNestedRun } from './fixture-child.js';import assert from 'node:assert/strict';import { spawn } from 'node:child_process';import { chmodSync, copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs';@@ -173,6 +174,11 @@ function scenario(box, mode, { dropOnce } = {}) {* group. Past its deadline the whole group is stopped and the scenario fails naming itself.*/async function landingGate(box, label, deadlineMs, repo = box.repo) {+ return await awaitNestedRun(startLandingGate(box, label, deadlineMs, repo));+}++/** Start a landing immediately; callers may start several before lending their one place serially. */+function startLandingGate(box, label, deadlineMs, repo = box.repo) {const gateUrl = pathToFileURL(join(repo, 'src', 'gate.js')).href;const configUrl = pathToFileURL(join(repo, 'src', 'config.js')).href;const script = `const { runGate } = await import(${JSON.stringify(gateUrl)});@@ -186,17 +192,24 @@ process.stdout.write(JSON.stringify({ isGreen: gate.isGreen, output: gate.outputchild.stdout.setEncoding('utf8').on('data', part => { stdout += part; });child.stderr.setEncoding('utf8').on('data', part => { stderr += part; });const closed = new Promise(resolveClose => child.once('close', (status, signal) => resolveClose({ status, signal })));- let timer;- const deadline = new Promise(resolveDeadline => { timer = setTimeout(() => resolveDeadline(null), deadlineMs); });- const ended = await Promise.race([closed, deadline]);- clearTimeout(timer);- if (!ended) {- for (const signal of ['SIGTERM', 'SIGKILL']) { try { process.kill(-child.pid, signal); } catch { /* already gone */ } }- await closed;- throw new Error(`landing gate scenario "${label}" passed its ${deadlineMs} ms deadline\n${stdout.slice(-4_000)}\n${stderr.slice(-4_000)}`);- }- assert.equal(ended.status, 0, `scenario "${label}": the gate process failed\n${stderr.slice(-4_000)}`);- return { ...JSON.parse(stdout), stderr };+ // Deadline cancellation stays inside the helper, never outside a raced loan promise.+ const terminal = (async () => {+ let timer;+ const deadline = new Promise(resolveDeadline => { timer = setTimeout(() => resolveDeadline(null), deadlineMs); });+ const ended = await Promise.race([closed, deadline]);+ clearTimeout(timer);+ if (!ended) {+ for (const signal of ['SIGTERM', 'SIGKILL']) { try { process.kill(-child.pid, signal); } catch { /* already gone */ } }+ await closed;+ throw new Error(`landing gate scenario "${label}" passed its ${deadlineMs} ms deadline\n${stdout.slice(-4_000)}\n${stderr.slice(-4_000)}`);+ }+ assert.equal(ended.status, 0, `scenario "${label}": the gate process failed\n${stderr.slice(-4_000)}`);+ return { ...JSON.parse(stdout), stderr };+ })();+ terminal.child = child;+ // A sibling may finish before this promise gets its turn to borrow; retain its original rejection.+ void terminal.catch(() => {});+ return terminal;}/** The merged log's per-file lines as {file: {shard, host}}. */@@ -299,7 +312,14 @@ test('a landing gate split into shards reports one result [C7,V4]', { timeout: 3const pair = fixture({ runner: false, repoNames: ['first', 'second'] });t.after(() => rmSync(pair.dir, { recursive: true, force: true }));scenario(pair, 'green');- const both = await Promise.all(pair.repos.map((repo, index) => landingGate(pair, `concurrent landing ${index + 1}`, 120_000, repo)));+ const started = pair.repos.map((repo, index) => startLandingGate(pair, `concurrent landing ${index + 1}`, 120_000, repo));+ const both = [];+ let firstFailure;+ for (const terminal of started) {+ try { both.push(await awaitNestedRun(terminal)); }+ catch (error) { firstFailure ??= error; }+ }+ if (firstFailure) throw firstFailure;for (const landing of both) {assert.equal(landing.isGreen, true, landing.output);assert.equal(Object.keys(mergedFiles(landing.output)).length, 6);@@ -342,16 +362,20 @@ process.stdout.write(JSON.stringify({ isGreen: result.isGreen, output, calls, prchild.stdout.setEncoding('utf8').on('data', part => { stdout += part; });child.stderr.setEncoding('utf8').on('data', part => { stderr += part; });const closed = new Promise(resolveClose => child.once('close', status => resolveClose({ status })));- let timer;- const ended = await Promise.race([closed, new Promise(resolveDeadline => { timer = setTimeout(() => resolveDeadline(null), deadlineMs); })]);- clearTimeout(timer);- if (!ended) {- for (const signal of ['SIGTERM', 'SIGKILL']) { try { process.kill(-child.pid, signal); } catch { /* already gone */ } }- await closed;- throw new Error(`runner answer "${answer}" passed its ${deadlineMs} ms deadline\n${stderr.slice(-4_000)}`);- }- assert.equal(ended.status, 0, `runner answer "${answer}": the landing process failed\n${stderr.slice(-4_000)}`);- return JSON.parse(stdout);+ const terminal = (async () => {+ let timer;+ const ended = await Promise.race([closed, new Promise(resolveDeadline => { timer = setTimeout(() => resolveDeadline(null), deadlineMs); })]);+ clearTimeout(timer);+ if (!ended) {+ for (const signal of ['SIGTERM', 'SIGKILL']) { try { process.kill(-child.pid, signal); } catch { /* already gone */ } }+ await closed;+ throw new Error(`runner answer "${answer}" passed its ${deadlineMs} ms deadline\n${stderr.slice(-4_000)}`);+ }+ assert.equal(ended.status, 0, `runner answer "${answer}": the landing process failed\n${stderr.slice(-4_000)}`);+ return JSON.parse(stdout);+ })();+ terminal.child = child;+ return await awaitNestedRun(terminal);}test('a runner refusal in a sharded landing is handled by its class [C7,V4]', { timeout: 300_000 }, async (t) => { // budget: five bounded landings on one fixture.diff --git a/test/resources.test.js b/test/resources.test.jsindex 0266171c..bc9f3753 100644--- a/test/resources.test.js+++ b/test/resources.test.js@@ -1,6 +1,7 @@/** @pullboard-test-input source-tree *//** @pullboard-test-loads src/cli.js *//** Real-process resource queue and lease coverage [Q1,Q2,Q3]. */+import { awaitNestedRun } from './fixture-child.js';import assert from 'node:assert/strict';import { startFixtureChild as spawn, runFixtureChild as spawnSync, reportFixtureChildFailure, runFixtureChild, runFixtureChildAsync, runFixtureGit } from './fixture-child.js';import { performance } from 'node:perf_hooks';@@ -19,7 +20,6 @@ import { checkNeedsBrowser } from '../src/browser-admission.js';import { releaseQueueProof } from './resources-release-fixture.js';import { openPrivateScopedView, queuedLeaseProof, resourceNames, resourceWorkerSources } from './resources-lease-fixture.js';import { checkProject, verificationProject } from './resources-verify-fixture.js';-const TEMP = [];const CHILDREN = new Set();const MODULE = pathToFileURL(resolve(import.meta.dirname, '../src/resources.js')).href;@@ -1744,7 +1744,7 @@ test('a gate-slot waiter retries a locked slot database [C7]', async () => {return { done: locker, pid: locker.child.pid, stop: () => locker.child.kill('SIGKILL') };};/** Run one named test file through the real runner, which waits for a machine gate slot. */- const runWaiter = () => runFixtureChildAsync(process.execPath, [TEST_RUNNER, 'ran.test.js'], { cwd: box.first, env });+ const runWaiter = () => awaitNestedRun(runFixtureChildAsync(process.execPath, [TEST_RUNNER, 'ran.test.js'], { cwd: box.first, env }));const shortLock = await holdLock(3_000);const kept = await runWaiter();diff --git a/test/runner-browser-free-fixture.js b/test/runner-browser-free-fixture.jsindex e3e74a11..a03ad639 100644--- a/test/runner-browser-free-fixture.js+++ b/test/runner-browser-free-fixture.js@@ -1,5 +1,6 @@/** @pullboard-test-input source-tree *//** A runner registered with no browser slots runs browser-free test files and never browser-bound ones [C7]. */+import { awaitNestedRun } from './fixture-child.js';import assert from 'node:assert/strict';import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';import { join, resolve } from 'node:path';@@ -100,7 +101,7 @@ export async function browserFreeRunnerCheck(t, helpers) {await withNoBrowserRunner(t, helpers, async (fixture) => {const { runTests, show, hold, free } = fixture;await hold();- const ran = await runTests('test/free.test.js');+ const ran = await awaitNestedRun(runTests('test/free.test.js'));assert.doesNotMatch(ran.stdout + ran.stderr, /BROWSER_SLOT_REQUIRED/u, show(ran));assert.equal(ran.status, 0, show(ran));assert.match(ran.stdout, /^ok 1 - browser-free file ran/mu, show(ran));@@ -112,7 +113,7 @@ export async function browserFreeRunnerCheck(t, helpers) {const pending = gateRun(fixture, command);await until(() => fixture.phases().returned === 2, 'the runner answers the refused run');free();- const rerun = await pending;+ const rerun = await awaitNestedRun(pending);assert.equal(rerun.status, 0, show(rerun));assert.match(rerun.stderr, /RUNNER_BROWSER_SLOT_REQUIRED[^\n]*its attempt \(exit 1\):\n[^]*run-tests: \[BROWSER_SLOT_REQUIRED\][^]*rerunning it locally with a browser slot/u, show(rerun));const record = JSON.parse(rerun.stdout.split('\n').findLast(line => line.startsWith('PULLBOARD_RUN_RESULT ')).slice('PULLBOARD_RUN_RESULT '.length));@@ -130,7 +131,7 @@ export async function browserFreeRunnerCheck(t, helpers) {await new Promise(resolveWait => setTimeout(resolveWait, 1_000)); // budget: several admission polls in which a runner could take it.assert.equal(waiting(), true, 'the browser-bound run still waits for a local slot');free();- const local = await bound;+ const local = await awaitNestedRun(bound);assert.equal(local.status, 0, show(local));assert.match(local.stdout, /^ok 1 - browser-bound file ran/mu, show(local));assert.deepEqual(fixture.phases(), { dispatched: 2, returned: 2 }, 'the browser-bound file never reached the runner');@@ -142,7 +143,7 @@ export async function browserRefusalTextStaysRed(t, helpers) {await withNoBrowserRunner(t, helpers, async (fixture) => {const { runTests, show, hold } = fixture;await hold();- const red = await runTests('test/marker.test.js');+ const red = await awaitNestedRun(runTests('test/marker.test.js'));assert.equal(red.status, 1, show(red));assert.match(red.stdout, /^not ok 1 - marker file ran/mu, show(red));assert.match(red.stdout, /\[BROWSER_SLOT_REQUIRED\] thrown by a test/u, show(red));diff --git a/test/runner-pid.test.js b/test/runner-pid.test.jsindex e9b79564..12324b2b 100644--- a/test/runner-pid.test.js+++ b/test/runner-pid.test.js@@ -6,6 +6,7 @@ import { tmpdir } from 'node:os';import { join } from 'node:path';import { fileURLToPath } from 'node:url';import { test } from 'node:test';+import { awaitNestedRun } from '../src/test-file-pool.js';const runner = fileURLToPath(new URL('../bin/run-tests.js', import.meta.url));@@ -20,13 +21,14 @@ import { test } from 'node:test';test('inner', () => { appendFileSync(${JSON.stringify(seen)}, JSON.stringify({ who: 'inner', runner: process.env.PULLBOARD_TEST_RUNNER_PID }) + '\\n'); });`);writeFileSync(outer, `import { appendFileSync } from 'node:fs';+import { awaitNestedRun } from ${JSON.stringify(new URL('../src/test-file-pool.js', import.meta.url).href)};import { spawn } from 'node:child_process';import { test } from 'node:test';test('outer', async () => {appendFileSync(${JSON.stringify(seen)}, JSON.stringify({ who: 'outer', runner: process.env.PULLBOARD_TEST_RUNNER_PID }) + '\\n');const nested = spawn(process.execPath, [${JSON.stringify(runner)}, ${JSON.stringify(inner)}], { stdio: 'ignore' });appendFileSync(${JSON.stringify(seen)}, JSON.stringify({ who: 'nested runner', pid: String(nested.pid) }) + '\\n');- const code = await new Promise((done) => nested.once('close', done));+ const { status: code } = await awaitNestedRun(nested);if (code !== 0) throw new Error('the nested run failed with ' + code);});`);@@ -34,7 +36,7 @@ test('outer', async () => {let output = '';child.stdout.setEncoding('utf8').on('data', (part) => { output += part; });child.stderr.setEncoding('utf8').on('data', (part) => { output += part; });- const code = await new Promise((done) => child.once('close', done));+ const { status: code } = await awaitNestedRun(child);assert.equal(code, 0, output);const records = readFileSync(seen, 'utf8').trim().split('\n').map((line) => JSON.parse(line));const by = (who) => records.find((record) => record.who === who);diff --git a/test/runner-tooling-fixture.js b/test/runner-tooling-fixture.jsindex b6de9171..210f6d0a 100644--- a/test/runner-tooling-fixture.js+++ b/test/runner-tooling-fixture.js@@ -1,4 +1,5 @@/** Shared registered-runner test tooling and bounded round-trip helpers. */+import { awaitNestedRun } from './fixture-child.js';import assert from 'node:assert/strict';import { copyFileSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs';import { join, resolve } from 'node:path';@@ -108,7 +109,17 @@ export function phaseCounts(file) {* passes the marker counts it read before spawning the child: a fast child can dispatch before this* function first runs, and a baseline read here would swallow that dispatch.*/-export async function awaitRoundTrip(child, closed, phasesFile, before, deadlines = ROUND_TRIP_DEADLINES, firstReceiptAccepted = null) {+export function awaitRoundTrip(child, closed, phasesFile, before, deadlines = ROUND_TRIP_DEADLINES, firstReceiptAccepted = null) {+ const terminal = monitorRoundTrip(child, closed, phasesFile, before, deadlines, firstReceiptAccepted).catch(async error => {+ if (child.exitCode === null && child.signalCode === null) await stopGroup(child, closed);+ throw error;+ });+ terminal.child = child;+ return awaitNestedRun(terminal);+}++/** Monitor the owned child's progress and cancellation inside its single explicit yielding wait. */+async function monitorRoundTrip(child, closed, phasesFile, before, deadlines, firstReceiptAccepted) {const limits = { ...ROUND_TRIP_DEADLINES, ...deadlines };let done = null;closed.then(result => { done = result; });diff --git a/test/test-isolation.test.js b/test/test-isolation.test.jsindex 465b1ec0..5df29bd4 100644--- a/test/test-isolation.test.js+++ b/test/test-isolation.test.js@@ -1,5 +1,6 @@/** @pullboard-test-loads bin/run-tests.js src/test-isolation.js src/child-journal-preload.js src/machine-home.js src/settings.js src/resources.js src/view-port.js *//** A test's verdict never depends on the machine it runs on: settings, resources, runners, host markers, ports [C7]. */+import { awaitNestedRun } from './fixture-child.js';import assert from 'node:assert/strict';import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';import { createServer } from 'node:net';@@ -100,14 +101,14 @@ test('a test reads no machine state outside its own private home [C7]', async (tconst machine = { ...base, PULLBOARD_ACCOUNT_HOME: hostile, CI: '1', NODE_OPTIONS: runnerImport,PULLBOARD_RUNNER_PRELOAD: runnerImport, PULLBOARD_VIEW_PORT: '4891' };- const calm = await runFixtureChildAsync(process.execPath, [RUNNER, 'test/probe.test.js'], { cwd: root, env: plain });- const busy = await runFixtureChildAsync(process.execPath, [RUNNER, 'test/probe.test.js'], { cwd: root, env: machine });+ const calm = await awaitNestedRun(runFixtureChildAsync(process.execPath, [RUNNER, 'test/probe.test.js'], { cwd: root, env: plain }));+ const busy = await awaitNestedRun(runFixtureChildAsync(process.execPath, [RUNNER, 'test/probe.test.js'], { cwd: root, env: machine }));assert.deepEqual(verdicts(calm.stdout), PROBES.map((name, index) => `ok ${index + 1} - ${name}`), calm.stdout + calm.stderr);assert.deepEqual(verdicts(busy.stdout), verdicts(calm.stdout), `hostile machine settings changed a verdict:\n${busy.stdout}${busy.stderr}`);assert.equal(busy.status, 0, busy.stderr);// The probes are a real guard: run without the private home, the same suite reads the hostile machine and fails.- const exposed = await runFixtureChildAsync(process.execPath, ['--test', '--test-reporter=tap', 'test/probe.test.js'], { cwd: root, env: machine });+ const exposed = await awaitNestedRun(runFixtureChildAsync(process.execPath, ['--test', '--test-reporter=tap', 'test/probe.test.js'], { cwd: root, env: machine }));assert.notEqual(exposed.status, 0, 'a test that reads the machine home fails the guard');const seen = verdicts(exposed.stdout);for (const index of [0, 1, 2]) assert.match(seen[index], /^not ok /u, `${PROBES[index]} catches the machine it reads`);diff --git a/test/view-port.test.js b/test/view-port.test.jsindex 9244f9ab..87a67abc 100644--- a/test/view-port.test.js+++ b/test/view-port.test.js@@ -1,4 +1,5 @@/** Keep the view's exact named-port refusal covered in a core-owned file [N26]. */+import { awaitNestedRun } from './fixture-child.js';import assert from 'node:assert/strict';import { createHash, randomUUID } from 'node:crypto';import { execFileSync } from 'node:child_process';@@ -100,10 +101,10 @@ test('the suite runs while a view holds the default port [N26,C7]', async (t) =>'pullboard view uses its fixed default port and reuses its authenticated listener','a reused authenticated view completes setup for its new board',];- const result = await runFixtureChildAsync(process.execPath, [+ const result = await awaitNestedRun(runFixtureChildAsync(process.execPath, [resolve(import.meta.dirname, '../bin/run-tests.js'), '--test-name-pattern', names.join('|'),resolve(import.meta.dirname, 'view-port.test.js'), resolve(import.meta.dirname, 'resume-flow.test.js'),- ], { cwd: resolve(import.meta.dirname, '..'), env: { ...process.env } });+ ], { cwd: resolve(import.meta.dirname, '..'), env: { ...process.env } }));if (result.status !== 0) t.diagnostic(safeErrorSummary(result.stdout));assert.equal(result.status, 0, result.failure ?? result.stderr);for (const name of names) {