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): a stopped shard drains its detached descendants [C7,V4]

Corey Olsond0dca0c94024
diff --git a/bin/run-tests.js b/bin/run-tests.js
index 4069a778..a2cd2931 100644
--- a/bin/run-tests.js
+++ b/bin/run-tests.js
@@ -1036,6 +1036,11 @@ async function runLandingTests(args, env, concurrency) {
})().then(resolveAbort, error => { reporterError ??= error; resolveAbort(); });
return abortPromise;
};
+ // A shard the landing stops gets TERM: stop through the same custody as a first failure, so every
+ // owned descendant, detached ones included, is drained or named before this process exits.
+ let stoppedByLanding = false;
+ const stopShard = () => { stoppedByLanding = true; abortLandingRun(); };
+ if (process.env[LANDING_SHARD_ENV]) process.on('SIGTERM', stopShard);
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' });
@@ -1112,8 +1117,14 @@ async function runLandingTests(args, env, concurrency) {
endReporters();
for (const key of Object.keys(process.env)) delete process.env[key];
Object.assign(process.env, originalEnv);
+ process.off('SIGTERM', stopShard);
}
if (reporterError) throw reporterError;
+ if (stoppedByLanding && !firstFailure) {
+ process.stderr.write(`\nLanding shard ${process.env[LANDING_SHARD_ENV]} stopped by the landing after another shard failed; its owned processes were drained\n`);
+ process.exitCode = 1;
+ return { status: 1, signal: null };
+ }
if (firstFailure) {
const diagnostic = failureDiagnostics.get(firstFailure.file);
if (diagnostic) firstFailure = { file: firstFailure.file, name: diagnostic.name, error: diagnostic.details.error };
diff --git a/docs/api.md b/docs/api.md
index e574df6a..d0c85772 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -334,7 +334,7 @@ Row approval and decline first record the person's exact decision through the sa
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. If a process-identity census stays unavailable, tests still determine the gate result; the runner reports cleanup as `UNVERIFIED` and does not signal processes whose identity it could not establish. A `UNVERIFIED` cleanup report means descendant cleanup was not confirmed.
-With `landingShards: N` in `pullboard.json` (a whole number from 1 to 64; absent or 1 keeps one run), the landing run of `bin/run-tests.js` splits the tracked test files into N shards. It balances them by each file's wall time from the last sharded landing, kept in the repository's `pullboard/landing-file-times.json`; with no times it balances by file count. The first shard uses the gate's own slot. Each other shard takes a landing-priority gate slot, locally or on a registered runner. The run is green only if every shard is green. The first red shard stops the others, which are reported as `stopped`. A shard whose runner fails mid-run prints `landing shard <i>/<n>: runner <host> failed mid-shard; rerunning shard <i>/<n> locally` and reruns on a local slot. Runner refusals are classed by code. `RUNNER_SETUP_REFUSED` and `RESOURCE_LEASE_LOST` rerun locally, with the code and host in the log. `RUNNER_CLEANUP_TIMEOUT` reruns locally and also quarantines that host for the rest of the landing, printing `landing runner <host> quarantined for the rest of this landing: <message>`. `RUNNER_SOURCE_CHANGED` and any unknown code fail the landing red as `refused`, with no retry. The landing pins its source (HEAD, tracked changes and untracked files) before the first shard. A local shard, first run or rerun, checks that source before and after it runs and refuses as `LANDING_SOURCE_CHANGED` if the checkout moved, so a result never comes from other code. The merged log prints one `# landing shard <i>/<n> on <host>: <green|red|stopped> in <ms> ms` line per shard and one `# landing file <i>/<n> <host> <ms|-> <path>` line per file. It also names how the plan was balanced (`history`, `history and average` or `file count`) and, once history exists, the slowest recorded file as `# landing floor: <ms> ms <path>`, since no shard count can finish sooner. The gate profile carries the same fields as `landingShards.balance`, `landingShards.floor`, `landingShards.shards` and `landingShards.files`. Every shard takes any free gate slot, so a runner with two slots can run two shards, and each local shard needing Chrome still waits for the machine's `browserSlots`.
+With `landingShards: N` in `pullboard.json` (a whole number from 1 to 64; absent or 1 keeps one run), the landing run of `bin/run-tests.js` splits the tracked test files into N shards. It balances them by each file's wall time from the last sharded landing, kept in the repository's `pullboard/landing-file-times.json`; with no times it balances by file count. The first shard uses the gate's own slot. Each other shard takes a landing-priority gate slot, locally or on a registered runner. The run is green only if every shard is green. The first red shard stops the others, which are reported as `stopped`. A shard whose runner fails mid-run prints `landing shard <i>/<n>: runner <host> failed mid-shard; rerunning shard <i>/<n> locally` and reruns on a local slot. Runner refusals are classed by code. `RUNNER_SETUP_REFUSED` and `RESOURCE_LEASE_LOST` rerun locally, with the code and host in the log. `RUNNER_CLEANUP_TIMEOUT` reruns locally and also quarantines that host for the rest of the landing, printing `landing runner <host> quarantined for the rest of this landing: <message>`. `RUNNER_SOURCE_CHANGED` and any unknown code fail the landing red as `refused`, with no retry. The landing pins its source (HEAD, tracked changes and untracked files) before the first shard. A local shard, first run or rerun, checks that source before and after it runs and refuses as `LANDING_SOURCE_CHANGED` if the checkout moved, so a result never comes from other code. Stopping a local shard first records every process it owns from the process census: its parent-tree descendants, including detached ones in their own group or session, and their group members. It then sends TERM so the shard's run-tests drains through its own custody, and signals whatever the census still finds. Processes that cannot be shown gone are named as `[LANDING_SHARD_CLEANUP_UNVERIFIED]` in the log and in `landingShards.unverified`, with an instruction to inspect them before another run. The merged log prints one `# landing shard <i>/<n> on <host>: <green|red|stopped> in <ms> ms` line per shard and one `# landing file <i>/<n> <host> <ms|-> <path>` line per file. It also names how the plan was balanced (`history`, `history and average` or `file count`) and, once history exists, the slowest recorded file as `# landing floor: <ms> ms <path>`, since no shard count can finish sooner. The gate profile carries the same fields as `landingShards.balance`, `landingShards.floor`, `landingShards.shards` and `landingShards.files`. Every shard takes any free gate slot, so a runner with two slots can run two shards, and each local shard needing Chrome still waits for the machine's `browserSlots`.
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 07324c44..bd0bee5b 100644
--- a/src/gate.js
+++ b/src/gate.js
@@ -310,6 +310,8 @@ export function writeTimingProfile(path, profile) {
...(profile.executionRunner ? { executionRunner: sanitize(profile.executionRunner, 'execution runner') } : {}),
...(profile.landingShards ? { landingShards: {
balance: sanitize(String(profile.landingShards.balance ?? 'unknown'), 'landing balance'),
+ unverified: (profile.landingShards.unverified ?? []).map(entry => ({ shard: sanitize(String(entry.shard), 'landing unverified shard'),
+ processes: sanitize(String(entry.processes), 'landing unverified processes') })),
quarantined: (profile.landingShards.quarantined ?? []).map(entry => ({ host: sanitize(String(entry.host), 'landing quarantine host'),
message: sanitize(String(entry.message), 'landing quarantine message') })),
floor: profile.landingShards.floor && validDuration(profile.landingShards.floor.ms)
diff --git a/src/landing-shards.js b/src/landing-shards.js
index a75fa957..ebf49342 100644
--- a/src/landing-shards.js
+++ b/src/landing-shards.js
@@ -8,6 +8,7 @@ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from '
import { dirname, join } from 'node:path';
import { createHash, randomUUID } from 'node:crypto';
import { gitChildEnv, repoInfo } from './git.js';
+import { parseProcessCensus } from './process-census.js';
import {
BROWSER_SLOT_HELD_ENV,
GATE_SLOT_HELD_ENV,
@@ -24,8 +25,11 @@ export const LANDING_FILE_TIMES_ENV = 'PULLBOARD_LANDING_FILE_TIMES';
export const FILE_TIME_LINE = '# landing-file-ms ';
const GATE_MARKERS = [GATE_SLOT_HELD_ENV, GATE_SLOT_POOL_ENV, GATE_SLOT_TOKEN_ENV, BROWSER_SLOT_HELD_ENV];
-// Budget: a stopped local shard gets this long to drain after TERM before its group is killed.
-const STOP_GRACE_MS = 10_000;
+// Budget: a stopped shard's run-tests drains its owned processes within its 12 s custody limit; past
+// this its group is killed.
+const STOP_GRACE_MS = 20_000;
+// Budget: each signal round of the final sweep waits this long for a process to go.
+const SWEEP_WAIT_MS = 1_000;
/** Where the last landing's per-file wall times live, shared by every worktree of the repository. */
export function fileTimesPath(root) {
@@ -131,14 +135,78 @@ function word(value) {
return `'${String(value).replaceAll("'", "'\\''")}'`;
}
-/** Stop a detached shard's whole process group: TERM, then KILL after its grace. */
-async function stopGroup(child, closed) {
- const signal = name => { try { process.kill(-child.pid, name); } catch (error) { if (error.code !== 'ESRCH') throw error; } };
- signal('SIGTERM');
- const timer = setTimeout(() => signal('SIGKILL'), STOP_GRACE_MS);
- await closed;
+/** One process census, or null when it cannot be taken; a missing census is never an empty machine. */
+function census() {
+ const result = spawnSync('/bin/ps', ['-axo', 'pid=,ppid=,pgid=,lstart=,stat=,comm='], {
+ encoding: 'utf8', timeout: 5_000, maxBuffer: 16 * 1024 * 1024, env: { PATH: '/bin:/usr/bin', LANG: 'C', LC_ALL: 'C', TZ: 'UTC' } }); // budget: one bounded ps call.
+ if (result.error || result.status !== 0 || typeof result.stdout !== 'string') return null;
+ return parseProcessCensus(result.stdout);
+}
+
+/**
+ * Every process a shard owns: its parent-tree descendants, including detached ones that started
+ * their own group or session, plus every member of their groups. Taken before any signal, while the
+ * tree still links them, since an orphaned process loses its parent link.
+ */
+export function shardProcesses(rootPid, rows = census()) {
+ if (!rows) return null;
+ const owned = new Map();
+ const children = new Map();
+ for (const row of rows.values()) {
+ if (!children.has(row.ppid)) children.set(row.ppid, []);
+ children.get(row.ppid).push(row);
+ }
+ const queue = rows.has(rootPid) ? [rows.get(rootPid)] : [];
+ while (queue.length) {
+ const row = queue.shift();
+ if (owned.has(row.pid)) continue;
+ owned.set(row.pid, row);
+ queue.push(...(children.get(row.pid) ?? []));
+ }
+ const ownGroup = rows.get(process.pid)?.pgid;
+ const groups = new Set([...owned.values()].map(row => row.pgid).filter(pgid => pgid !== ownGroup));
+ for (const row of rows.values()) if (groups.has(row.pgid) && row.pid !== process.pid) owned.set(row.pid, row);
+ return owned;
+}
+
+/** The owned processes still alive with the same identity, or null when no census can tell. */
+function survivors(owned) {
+ const rows = census();
+ if (!rows) return null;
+ return [...owned.values()].filter(row => rows.get(row.pid)?.started === row.started);
+}
+
+/** Signal one process only while it is still the one the shard owned. */
+function signalOwned(row, name) {
+ try { process.kill(row.pid, name); } catch (error) { if (error.code !== 'ESRCH') throw error; }
+}
+
+/**
+ * Stop a shard and prove its processes are gone. TERM asks its run-tests to stop through its own
+ * custody, which drains every descendant it tracked; whatever the census still finds is signalled
+ * here. Returns the processes that could not be shown gone, named by pid and command hash.
+ */
+async function stopShard(child, closed) {
+ const owned = shardProcesses(child.pid);
+ signalOwned({ pid: child.pid }, 'SIGTERM');
+ let timer;
+ const drained = await Promise.race([closed.then(() => true), new Promise(resolveWait => { timer = setTimeout(() => resolveWait(false), STOP_GRACE_MS); })]);
clearTimeout(timer);
- signal('SIGKILL');
+ if (!drained) {
+ try { process.kill(-child.pid, 'SIGKILL'); } catch (error) { if (error.code !== 'ESRCH') throw error; }
+ await closed;
+ }
+ if (!owned) return ['process census unavailable'];
+ for (const name of ['SIGTERM', 'SIGKILL']) {
+ const left = survivors(owned);
+ if (!left) return ['process census unavailable'];
+ if (!left.length) return [];
+ for (const row of left) signalOwned(row, name);
+ await new Promise(resolveWait => setTimeout(resolveWait, SWEEP_WAIT_MS));
+ }
+ const left = survivors(owned);
+ if (!left) return ['process census unavailable'];
+ return left.map(row => `pid ${row.pid} (${row.processSha256.slice(0, 12)})`);
}
/** Run one shard's files in a local child run-tests that inherits the shard's own gate lease. */
@@ -154,12 +222,14 @@ async function runLocalShard({ root, runner, files, label, lease, stop }) {
child.once('error', error => { chunks.push(`\n${error.message}\n`); resolveClose({ status: 1, signal: null }); });
child.once('close', (status, signal) => resolveClose({ status, signal }));
});
- const onStop = () => { stopGroup(child, closed).catch(() => {}); };
+ let stopping = null;
+ const onStop = () => { stopping = stopShard(child, closed).catch(error => [`stop failed: ${error.message}`]); };
if (stop.aborted) onStop();
else stop.addEventListener('abort', onStop, { once: true });
const { status, signal } = await closed;
stop.removeEventListener('abort', onStop);
- return { isGreen: status === 0 && !signal, output: chunks.join('') };
+ const unverified = stopping ? await stopping : [];
+ return { isGreen: status === 0 && !signal && !stopping, output: chunks.join(''), unverified };
}
/**
@@ -269,6 +339,10 @@ export async function runLandingShards({ root, runner, files, count, inherited =
};
if (drifted()) return sourceChanged('before');
const run = await runLocalShard({ root, runner, files: entry.shard.files, label: entry.label, lease, stop });
+ if (run.unverified.length) {
+ // Fail closed: name what may still run, as a runner's unverified cleanup does.
+ write(`landing shard ${entry.label}: [LANDING_SHARD_CLEANUP_UNVERIFIED] the stopped shard's processes could not be shown gone: ${run.unverified.join(', ')}; inspect and stop them before another run\n`);
+ }
if (!stop.aborted && drifted()) return sourceChanged('while');
return { attempt: number, host: 'local', outcome: run.isGreen ? 'green' : 'red', output: run.output, wallMs: Date.now() - started };
}
@@ -413,9 +487,12 @@ export function landingShardProfile(output) {
let balance = null;
let floor = null;
const quarantined = [];
+ const unverified = [];
for (const line of String(output).split(/\r?\n/u)) {
const plan = /^# landing shards: \d+ balanced by (history|history and average|file count) \(/u.exec(line);
if (plan) balance = plan[1];
+ const leftover = /^landing shard (\d+\/\d+): \[LANDING_SHARD_CLEANUP_UNVERIFIED\] the stopped shard's processes could not be shown gone: (.*); inspect/u.exec(line);
+ if (leftover) unverified.push({ shard: leftover[1], processes: leftover[2] });
const held = /^landing runner (\S+) quarantined for the rest of this landing: (.*)$/u.exec(line);
if (held) quarantined.push({ host: held[1], message: held[2] });
const slowest = /^# landing floor: (\d+) ms (.+)$/u.exec(line);
@@ -425,7 +502,7 @@ export function landingShardProfile(output) {
const file = /^# landing file (\d+\/\d+) (\S+) (\d+|-) (.+)$/u.exec(line);
if (file) files.push({ path: file[4], shard: file[1], host: file[2], durationMs: file[3] === '-' ? null : Number(file[3]) });
}
- return shards.length ? { balance, floor, quarantined, shards, files } : null;
+ return shards.length ? { balance, floor, quarantined, unverified, shards, files } : null;
}
/** Print this shard's per-file wall times for its orchestrator; a missing record prints nothing. */
diff --git a/test/landing-shards.test.js b/test/landing-shards.test.js
index 0a278b31..ede086b1 100644
--- a/test/landing-shards.test.js
+++ b/test/landing-shards.test.js
@@ -374,3 +374,63 @@ test('a runner refusal in a sharded landing is handled by its class [C7,V4]', {
assert.doesNotMatch(moved.output, /attempt 2 on local: green/u, 'no green result comes from the changed checkout');
} finally { writeFileSync(edited, original); }
});
+
+/** Whether a pid still names a live process; a permission error still means it exists. */
+function alive(pid) {
+ try { process.kill(pid, 0); return true; }
+ catch (error) { return error.code === 'EPERM'; }
+}
+
+test('a stopped landing shard drains its detached descendant [C7,V4]', { timeout: 120_000 }, async (t) => { // budget: one stopped two-shard landing plus its owned-process sweep.
+ const box = fixture({ runner: false });
+ t.after(() => rmSync(box.dir, { recursive: true, force: true }));
+ scenario(box, 'green');
+ const ready = join(box.dir, 'detached-child-ready.json');
+ const survived = join(box.dir, 'detached-child-survived');
+ // The grandchild leaves the shard's process group and session, then writes its marker later.
+ const childCode = [
+ "import { writeFileSync } from 'node:fs';",
+ 'const writeAt = Date.now() + 3000;',
+ `writeFileSync(${JSON.stringify(ready)}, JSON.stringify({ pid: process.pid, writeAt }));`,
+ `setTimeout(() => writeFileSync(${JSON.stringify(survived)}, 'survived'), writeAt - Date.now());`,
+ 'setInterval(() => {}, 1000);',
+ ].join('\n');
+ const failing = `import { test } from 'node:test';
+import { existsSync } from 'node:fs';
+test('fail once the other shard owns its detached child', async () => {
+ while (!existsSync(${JSON.stringify(ready)})) await new Promise(resolve => setTimeout(resolve, 25));
+ throw new Error('deliberate first shard failure');
+});
+`;
+ const owner = `import { test } from 'node:test';
+import { spawn } from 'node:child_process';
+test('own a detached child', async () => {
+ const child = spawn(process.execPath, ['--input-type=module', '-e', ${JSON.stringify(childCode)}], { detached: true, stdio: 'ignore' });
+ child.unref();
+ await new Promise(resolve => setTimeout(resolve, 60_000));
+});
+`;
+ // Two shards: a.test.js alone fails, b.test.js owns the detached grandchild.
+ for (const name of NAMES.slice(2)) rmSync(join(box.repo, 'test', `${name}.test.js`));
+ writeFileSync(join(box.repo, 'test', 'a.test.js'), failing);
+ writeFileSync(join(box.repo, 'test', 'b.test.js'), owner);
+ writeFileSync(join(box.repo, 'pullboard.json'), JSON.stringify({ gate: 'node bin/run-tests.js', landingShards: 2 }));
+ git(box.repo, box.env, 'add', '-A');
+ git(box.repo, box.env, 'commit', '-q', '-m', 'test: a shard owns a detached descendant');
+ let pid = null;
+ try {
+ const result = await landingGate(box, 'stopped shard with a detached descendant', 90_000);
+ assert.equal(result.isGreen, false, result.output);
+ assert.ok(existsSync(ready), 'the detached grandchild started before the stop');
+ ({ pid } = JSON.parse(readFileSync(ready, 'utf8')));
+ assert.equal(alive(pid), false, `no process from the stopped shard survives the landing\n${result.output}`);
+ assert.doesNotMatch(result.output, /LANDING_SHARD_CLEANUP_UNVERIFIED/u, 'its cleanup was verified');
+ const { writeAt } = JSON.parse(readFileSync(ready, 'utf8'));
+ // budget: wait past the grandchild's own write time, read from its marker, before judging the file.
+ while (Date.now() <= writeAt + 500) await new Promise(resolve => setTimeout(resolve, 100));
+ assert.equal(existsSync(survived), false, 'the stopped grandchild never wrote its marker');
+ } finally {
+ // Only the fixture's own recorded grandchild is ever signalled here.
+ if (pid && alive(pid)) process.kill(pid, 'SIGKILL');
+ }
+});