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(runners): preserve fresh setup and owned capacity [C7]

Corey Olsonce36ac3422a0
diff --git a/docs/api.md b/docs/api.md
index e342c72f..caee9c65 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -319,4 +319,6 @@ The view's own page retains its person channel. The standalone API refuses `POST
`runner add` registers machine-local SSH capacity. Optional `--node` and `--root` select absolute remote paths when Node is outside the SSH login path or runner storage needs a specific location. The default storage root is `~/.pullboard-runner`; runner work shares the remote machine resource pool.
-Runner storage keeps one repository object cache and creates an isolated checkout per run. A locked inventory handshake transfers only missing committed objects after scanning their blobs, paths and commit metadata, including ancestors. Credential-free HTTPS origins may seed the cache anonymously; caller credentials are never forwarded.
+Runner storage keeps one repository object cache and creates an isolated checkout with complete history per run. A locked inventory handshake transfers only missing committed objects after scanning their blobs, paths and commit metadata, including ancestors. Historical protected paths are checked before connecting. A credential-free HTTPS origin may seed the cache at a locally known published ancestor; caller credentials are never forwarded. Cached object contents are not rescanned on every run.
+
+Each checkout with a committed npm lockfile runs `npm ci`, including lifecycle scripts. Only npm's content cache is shared; installed dependencies and generated files stay in the fresh checkout. Other lock managers are refused. Combined command output and transport diagnostics are bounded at 64 MiB; exceeding that limit refuses the run.
diff --git a/src/resources.js b/src/resources.js
index 48c706a9..612fbdd1 100644
--- a/src/resources.js
+++ b/src/resources.js
@@ -20,8 +20,12 @@ export const GATE_SLOT_POOL_ENV = 'PULLBOARD_GATE_SLOT_POOL';
export const GATE_SLOT_TOKEN_ENV = 'PULLBOARD_GATE_SLOT_TOKEN';
export const BROWSER_SLOT_HELD_ENV = 'PULLBOARD_BROWSER_SLOT_HELD';
+/** Reserve a distinct resource row for each configured remote host. */
+function runnerResourceName(host) { return `runner:${host}`; }
+
/** Build child markers that identify the exact machine queue lease and its browser capacity. */
export function gateSlotEnvironment(lease) {
+ if (lease?.runner) throw new Refused('REMOTE_GATE_SLOT_NOT_INHERITABLE', 'remote runner leases cannot be inherited through local gate markers');
if (!lease || lease.name !== 'gate' || lease.scope !== 'machine' || typeof lease.pool !== 'string' || typeof lease.token !== 'string') {
throw new Refused('GATE_SLOT_LEASE_REQUIRED', 'pass the live machine gate lease when starting a child test process');
}
@@ -90,6 +94,13 @@ function open(file) {
if (table === 'holder' && !columns.includes('runner')) db.exec("ALTER TABLE holder ADD COLUMN runner TEXT NOT NULL DEFAULT ''");
if (table === 'waiter' && !columns.includes('remote')) db.exec('ALTER TABLE waiter ADD COLUMN remote INTEGER NOT NULL DEFAULT 0');
}
+ // Older runner-aware builds stored remote leases as ordinary gate holders. Move them
+ // into their host namespace so old readers of name='gate' continue to see local use only.
+ db.exec(`INSERT INTO resource(name, capacity)
+ SELECT 'runner:' || runner, MAX(1, COUNT(*)) FROM holder
+ WHERE name = 'gate' AND runner <> '' GROUP BY runner
+ ON CONFLICT(name) DO NOTHING;
+ UPDATE holder SET name = 'runner:' || runner WHERE name = 'gate' AND runner <> '';`);
db.exec('COMMIT');
transaction = false;
} catch (error) {
@@ -184,7 +195,10 @@ function snapshot(db, name) {
// Browser is an additional capability on a gate lease, not a second partially held row.
const where = name === 'browser' ? 'name = ? AND browser = 1' : 'name = ?';
const sourceName = name === 'browser' ? 'gate' : name;
- const holders = db.prepare(`SELECT agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, runner, item, kind FROM holder WHERE ${where} ORDER BY since, token`).all(sourceName).map(project);
+ const runnerHost = name.startsWith('runner:') ? name.slice('runner:'.length) : '';
+ const holderWhere = runnerHost ? 'name = ?' : where;
+ const holderValues = [sourceName];
+ const holders = db.prepare(`SELECT agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, runner, item, kind FROM holder WHERE ${holderWhere} ORDER BY since, token`).all(...holderValues).map(project);
const line = db.prepare(`SELECT agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, remote, item, kind FROM waiter WHERE ${where} ORDER BY landing DESC, ticket`).all(sourceName).map(project);
return { holders, line };
}
@@ -235,13 +249,18 @@ function validatedRunners(value) {
/** Find the earliest compatible free executor while allowing CPU waiters past browser-only blocks. */
function gateAdmission(db, ticket, capacity, runners) {
const waiters = db.prepare("SELECT ticket, pid, landing, browser, remote FROM waiter WHERE name = 'gate' ORDER BY landing DESC, ticket").all();
- const holders = db.prepare("SELECT pid, landing, browser, runner FROM holder WHERE name = 'gate'").all();
- const localUsed = holders.filter(holder => !holder.runner).length;
- const localBrowsers = holders.filter(holder => !holder.runner && holder.browser === 1).length;
- const usage = new Map(runners.map(runner => [runner.host, {
- slots: holders.filter(holder => holder.runner === runner.host).length,
- browsers: holders.filter(holder => holder.runner === runner.host && holder.browser === 1).length,
- }]));
+ const holders = db.prepare("SELECT pid, landing, browser FROM holder WHERE name = 'gate'").all();
+ const localUsed = holders.length;
+ const localBrowsers = holders.filter(holder => holder.browser === 1).length;
+ const usage = new Map(runners.map(runner => {
+ // The reserved namespace is authoritative even for an older generic holder that
+ // predates the name guard and has no runner column value.
+ const remoteHolders = db.prepare('SELECT browser FROM holder WHERE name = ?').all(runnerResourceName(runner.host));
+ return [runner.host, {
+ slots: remoteHolders.length,
+ browsers: remoteHolders.filter(holder => holder.browser === 1).length,
+ }];
+ }));
const unavailable = new Set(db.prepare('SELECT host FROM runner_unavailable').all().map(row => row.host));
/** Keep an already holding process from taking another slot ahead of a different landing. */
const blockedByLanding = waiter => holders.some(holder => holder.pid === waiter.pid)
@@ -262,6 +281,16 @@ function gateAdmission(db, ticket, capacity, runners) {
}
return null;
}
+ for (const runner of runners) {
+ const resourceName = runnerResourceName(runner.host);
+ const row = db.prepare('SELECT capacity FROM resource WHERE name = ?').get(resourceName);
+ const held = usage.get(runner.host).slots;
+ if (!row) db.prepare('INSERT INTO resource(name, capacity) VALUES (?, ?)').run(resourceName, runner.slots);
+ else if (row.capacity !== runner.slots) {
+ if (held > runner.slots) throw new Refused('RUNNER_CAPACITY_MISMATCH', `runner ${runner.host} has ${held} active slot(s), more than configured capacity ${runner.slots}`);
+ db.prepare('UPDATE resource SET capacity = ? WHERE name = ?').run(runner.slots, resourceName);
+ }
+ }
for (const waiter of waiters) {
const executor = available(waiter);
if (executor) return waiter.ticket === ticket ? executor : null;
@@ -275,7 +304,8 @@ export function runnerResourceStatus(runners) {
const db = open(machineResourceFile());
try {
return update(db, () => configured.map(runner => {
- const holders = db.prepare("SELECT agent, repo, since, browser, item, kind FROM holder WHERE name = 'gate' AND runner = ? ORDER BY since, token").all(runner.host);
+ const holders = db.prepare('SELECT agent, repo, since, browser, item, kind, runner FROM holder WHERE name = ? ORDER BY since, token')
+ .all(runnerResourceName(runner.host));
const unavailable = db.prepare('SELECT since, detail FROM runner_unavailable WHERE host = ?').get(runner.host);
return { ...runner, inUse: holders.length, browserInUse: holders.filter(holder => holder.browser === 1).length,
unavailable: Boolean(unavailable), ...(unavailable ? { unavailableSince: unavailable.since, unavailableReason: unavailable.detail } : {}), holders };
@@ -291,9 +321,14 @@ export function updateRunnerSettings(host, persist) {
const db = open(machineResourceFile());
try {
return update(db, () => {
- const held = db.prepare("SELECT COUNT(*) AS count FROM holder WHERE name = 'gate' AND runner = ?").get(host).count;
+ const resourceName = runnerResourceName(host);
+ const held = db.prepare('SELECT COUNT(*) AS count FROM holder WHERE name = ?').get(resourceName).count;
if (held) throw new Refused('RUNNER_BUSY', `runner ${host} has ${held} active slot(s); wait for them to finish before changing its settings`);
const result = persist();
+ if (Number.isSafeInteger(result?.slots) && result.slots > 0) {
+ db.prepare('INSERT INTO resource(name, capacity) VALUES (?, ?) ON CONFLICT(name) DO UPDATE SET capacity = excluded.capacity')
+ .run(resourceName, result.slots);
+ }
db.prepare('DELETE FROM runner_unavailable WHERE host = ?').run(host);
return result;
});
@@ -312,12 +347,15 @@ function pause(ms) { return new Promise((resolvePromise) => setTimeout(resolvePr
export async function takeResource(options) {
const { name, capacity, scope = 'machine', root = process.cwd(), allowIdleCapacityUpdate = false } = options;
if (typeof name !== 'string' || !name.trim() || name.trim() !== name) throw new Refused('BAD_RESOURCE_NAME', 'resource name must be nonempty trimmed text');
+ if (name.startsWith('runner:')) throw new Refused('RESERVED_RUNNER_RESOURCE', 'runner resource rows are managed by the machine gate; request name "gate"');
if (!Number.isSafeInteger(capacity) || capacity < 1) throw new Refused('BAD_RESOURCE_CAPACITY', 'resource capacity must be a positive integer');
const landing = options.landing === true;
const itemCheck = options.itemCheck === true;
const diagnostic = options.diagnostic === true;
const browser = options.browser === true;
const remote = options.remote === true;
+ // This synchronous provider is used inside the admission transaction; callers must
+ // limit it to a bounded local configuration read, never Git, process inspection or network work.
const runnerProvider = options.runnerProvider;
const item = options.item ?? '';
const kind = options.kind ?? '';
@@ -370,8 +408,11 @@ export async function takeResource(options) {
}
});
while (true) {
- const runners = runnerProvider ? validatedRunners(runnerProvider()) : [];
const acquired = update(db, () => {
+ // The machine-settings provider performs a bounded local JSON read. Read it
+ // after taking the same SQLite write lock used by updateRunnerSettings so an
+ // older pre-lock snapshot cannot overwrite a newer configured capacity.
+ const runners = runnerProvider ? validatedRunners(runnerProvider()) : [];
const waiter = db.prepare('SELECT ticket FROM waiter WHERE token = ?').get(token);
if (!waiter) {
if (resume && initialTicket) {
@@ -393,7 +434,8 @@ export async function takeResource(options) {
if (executor) {
db.prepare('DELETE FROM waiter WHERE token = ?').run(token);
const acquiredAt = new Date().toISOString();
- db.prepare('INSERT INTO holder(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, runner) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, acquiredAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, executor.host);
+ const holderName = executor.host ? runnerResourceName(executor.host) : name;
+ db.prepare('INSERT INTO holder(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind, runner) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, holderName, pid, started, agent, repo, acquiredAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind, executor.host);
return { acquired: true, state: { ...spot, position: 0 }, ticket: waiter.ticket, runner: executor.host ? executor : undefined };
}
return { acquired: false, state: { ...spot, position: reportPosition } };
@@ -447,7 +489,8 @@ export async function takeResource(options) {
update(db, () => {
db.prepare('INSERT INTO runner_unavailable(host, since, detail) VALUES (?, ?, ?) ON CONFLICT(host) DO UPDATE SET since = excluded.since, detail = excluded.detail')
.run(acquired.runner.host, new Date().toISOString(), 'TRANSPORT_LOST');
- const holder = db.prepare('SELECT token FROM holder WHERE token = ?').get(token);
+ const holderName = runnerResourceName(acquired.runner.host);
+ const holder = db.prepare('SELECT token FROM holder WHERE token = ? AND name = ? AND runner = ?').get(token, holderName, acquired.runner.host);
if (!holder) throw new Refused('RESOURCE_LEASE_LOST', `remote lease for "${name}" is no longer held`);
const minimumTicket = db.prepare("SELECT MIN(ticket) AS ticket FROM waiter WHERE name = 'gate' AND landing = ?").get(Number(landing)).ticket;
requeueTicket = Math.min(0, minimumTicket ?? 0) - 1;
@@ -507,6 +550,7 @@ export function inheritedGateSlot({ root = process.cwd(), browser = false } = {}
/** Change a resource's capacity only while its queue is empty, persisting related settings under the same lock. */
export function setResourceCapacity({ name, capacity, scope = 'machine', root = process.cwd(), persist = () => {} }) {
if (typeof name !== 'string' || !name.trim() || name.trim() !== name) throw new Refused('BAD_RESOURCE_NAME', 'resource name must be nonempty trimmed text');
+ if (name.startsWith('runner:')) throw new Refused('RESERVED_RUNNER_RESOURCE', 'runner resource rows are managed by the machine gate; use runner settings');
if (!Number.isSafeInteger(capacity) || capacity < 1) throw new Refused('BAD_RESOURCE_CAPACITY', 'resource capacity must be a positive integer');
if (name === 'browser' && capacity !== 1) throw new Refused('BAD_RESOURCE_CAPACITY', 'browser resource capacity is fixed at 1');
const db = open(databaseFile(scope, root));
diff --git a/src/runner-worker.js b/src/runner-worker.js
index 4a2ccb30..5f2d83fc 100644
--- a/src/runner-worker.js
+++ b/src/runner-worker.js
@@ -1,7 +1,7 @@
/** Standalone SSH runner worker source; intentionally imports only Node built-ins. */
import { spawn, spawnSync } from 'node:child_process';
import { createHash } from 'node:crypto';
-import { chmodSync, cpSync, createReadStream, createWriteStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import { chmodSync, closeSync, createReadStream, createWriteStream, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, readSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { userInfo } from 'node:os';
import { delimiter, dirname, isAbsolute, join } from 'node:path';
import { pathToFileURL } from 'node:url';
@@ -18,6 +18,7 @@ let transportDrop = () => {};
let heartbeatTimer = null;
let workerId = 'starting';
let rejectPendingFrame = null;
+let activeDescendantTracker = null;
/** Parse and strictly validate the controller's one-shot work specification. */
async function readSpec() {
@@ -78,6 +79,9 @@ async function readSpec() {
throw new Error('invalid work specification');
}
}
+ if (value.originBase !== undefined
+ && (typeof value.originBase !== 'string' || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(value.originBase)
+ || value.originBase.length !== value.commit.length || !value.origin)) throw new Error('invalid work specification');
const runtimeNames = ['resources.js', 'git.js', 'machine-home.js', 'refused.js'];
if (Object.keys(value.runtime.files).length !== runtimeNames.length
|| runtimeNames.some(name => typeof value.runtime.files[name] !== 'string')) throw new Error('invalid work specification');
@@ -101,7 +105,7 @@ async function readSpec() {
}
/** Construct a minimal environment from runner-owned values, excluding caller credentials and markers. */
-function childEnvironment(home, temporary, machineHomePath = '') {
+function childEnvironment(home, temporary, machineHomePath = '', nodeOptions = '') {
return {
PATH: safePath,
HOME: home,
@@ -118,14 +122,15 @@ function childEnvironment(home, temporary, machineHomePath = '') {
GIT_OPTIONAL_LOCKS: '0',
NPM_CONFIG_USERCONFIG: join(home, 'npm-userconfig'),
NPM_CONFIG_GLOBALCONFIG: join(home, 'npm-globalconfig'),
+ ...(nodeOptions ? { NODE_OPTIONS: nodeOptions } : {}),
...(machineHomePath ? { PULLBOARD_MACHINE_HOME: machineHomePath } : {}),
};
}
/** Add this worker's remote gate lease so nested test runners reuse the remote slot instead of deadlocking. */
-function scopedEnvironment(home, temporary, machineHomePath, gateLease, resourcesApi) {
+function scopedEnvironment(home, temporary, machineHomePath, gateLease, resourcesApi, nodeOptions = '') {
return {
- ...childEnvironment(home, temporary, machineHomePath),
+ ...childEnvironment(home, temporary, machineHomePath, nodeOptions),
...resourcesApi.gateSlotEnvironment(gateLease),
};
}
@@ -163,19 +168,440 @@ function spawnOwned(command, args, options = {}) {
const closed = new Promise(resolveClose => { settle = resolveClose; });
const record = { child, pid: child.pid, closed, drainPromise: null };
ownedChildren.set(child, record);
+ activeDescendantTracker?.registerRoot(child.pid);
child.once('error', error => settle({ error }));
child.once('close', (code, signal) => settle({ code, signal }));
return record;
}
+/** Read one all-process POSIX census; a failed or malformed census is never interpreted as an empty machine. */
+function processCensus() {
+ const result = spawnSync('/bin/ps', ['-axo', 'pid=,ppid=,pgid=,lstart=,stat=,comm='], {
+ encoding: 'utf8', timeout: 2_000, maxBuffer: 8 * 1024 * 1024,
+ env: { PATH: safePath, LANG: 'C', LC_ALL: 'C', TZ: 'UTC' },
+ });
+ if (result.error || result.status !== 0 || typeof result.stdout !== 'string') return null;
+ const rows = new Map();
+ for (const line of result.stdout.split(/\r?\n/u)) {
+ if (!line.trim()) continue;
+ const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+([A-Z][a-z]{2})\s+([A-Z][a-z]{2})\s+(\d{1,2})\s+(\d{2}:\d{2}:\d{2})\s+(\d{4})\s+(\S+)\s+(.+?)\s*$/u.exec(line);
+ if (!match) return null;
+ const pid = Number(match[1]);
+ const ppid = Number(match[2]);
+ const pgid = Number(match[3]);
+ if (![pid, ppid, pgid].every(Number.isSafeInteger) || pid < 1 || ppid < 0 || pgid < 1 || rows.has(pid)) return null;
+ const started = `${match[4]} ${match[5]} ${match[6]} ${match[7]} ${match[8]}`;
+ const processSha256 = createHash('sha256').update(match[10]).digest('hex');
+ rows.set(pid, { pid, ppid, pgid, started, state: match[9], processSha256 });
+ }
+ return rows.size ? rows : null;
+}
+
+/** Add a kernel start-time identity when procfs is available; otherwise retain a conservative census tuple. */
+function processIdentity(row) {
+ let birth = '';
+ let exact = false;
+ try {
+ const stat = readFileSync(`/proc/${row.pid}/stat`, 'utf8');
+ const close = stat.lastIndexOf(')');
+ const fields = stat.slice(close + 2).trim().split(/\s+/u);
+ if (close > 0 && Number(fields[1]) === row.ppid && Number(fields[2]) === row.pgid && /^\d+$/u.test(fields[19] ?? '')) {
+ birth = `proc:${fields[19]}`;
+ exact = true;
+ }
+ } catch { /* macOS and other POSIX hosts use the validated census tuple below. */ }
+ if (!birth) birth = `ps:${row.started}`;
+ return { ...row, birth, exact };
+}
+
+/** Make a private Node preload that records only child identity and a one-way command digest. */
+function writeChildJournalPreload(directory) {
+ const journalDirectory = join(directory, 'child-journal');
+ mkdirSync(journalDirectory, { mode: 0o700 });
+ const overflowPath = join(journalDirectory, 'overflow');
+ const source = `
+import diagnostics from 'node:diagnostics_channel';
+import { closeSync, openSync, statSync, writeSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { createHash, randomUUID } from 'node:crypto';
+const directory = ${JSON.stringify(journalDirectory)};
+const overflowPath = ${JSON.stringify(overflowPath)};
+const instance = randomUUID();
+process.env.PULLBOARD_RUNNER_INSTANCE = instance;
+const file = join(directory, 'children-' + process.pid + '.jsonl');
+const fd = openSync(file, 'a', 0o600);
+let bytes = statSync(file).size;
+let overflow = false;
+const limit = 131072;
+function record(value) {
+ if (overflow) return;
+ try {
+ const line = JSON.stringify(value) + '\\n';
+ const size = Buffer.byteLength(line);
+ if (bytes + size > limit) {
+ overflow = true;
+ try { writeFileSync(overflowPath, 'journal limit reached\\n', { flag: 'wx', mode: 0o600 }); } catch {}
+ return;
+ }
+ writeSync(fd, line);
+ bytes += size;
+ } catch {
+ try { writeFileSync(overflowPath, 'journal write failed\\n', { flag: 'wx', mode: 0o600 }); } catch {}
+ overflow = true;
+ }
+}
+record({ type: 'boot', pid: process.pid, ppid: process.ppid, instance });
+const channel = diagnostics.channel('child_process');
+const seen = new WeakSet();
+channel.subscribe(message => {
+ try {
+ const child = message?.process;
+ if (!child || typeof child.once !== 'function' || seen.has(child)) return;
+ seen.add(child);
+ const writeReceipt = () => {
+ if (!Number.isSafeInteger(child.pid) || child.pid < 1) return;
+ const commandSha256 = createHash('sha256').update(JSON.stringify({ command: child.spawnfile ?? '', args: child.spawnargs ?? [] })).digest('hex');
+ record({ type: 'spawn', pid: child.pid, ppid: process.pid, instance, commandSha256 });
+ };
+ if (Number.isSafeInteger(child.pid)) writeReceipt();
+ else child.once('spawn', writeReceipt);
+ } catch {
+ try { writeFileSync(overflowPath, 'child receipt could not be recorded\\n', { flag: 'wx', mode: 0o600 }); } catch {}
+ }
+});
+process.once('exit', () => { try { closeSync(fd); } catch {} });
+`;
+ const preload = join(directory, 'child-spawn-preload.mjs');
+ writeFileSync(preload, source, { mode: 0o600, flag: 'wx' });
+ return { preload, journalDirectory, overflowPath, nodeOptions: `--import=${pathToFileURL(preload).href}` };
+}
+
+/** Track job descendants by PID plus OS start identity, joining spawn receipts with fresh census rows. */
+function createDescendantTracker(directory) {
+ const initial = processCensus();
+ if (!initial) throw new Error('initial process identity census failed');
+ const baseline = new Map([...initial].map(([pid, row]) => [pid, processIdentity(row)]));
+ const journal = writeChildJournalPreload(directory);
+ const roots = new Set();
+ const rootLaunchIdentities = new Map();
+ const known = new Map();
+ const retired = new Set();
+ const eventsByChild = new Map();
+ let eventCount = 0;
+ const detachedGroups = new Map();
+ const offsets = new Map();
+ const partial = new Map();
+ const instancePids = new Map();
+ const overflowPath = journal.overflowPath;
+ let current = baseline;
+ let uncertain = false;
+ let censusFailure = false;
+ let reason = '';
+ let busy = false;
+ let warned = false;
+ let timer = null;
+ let stoppingPromise = null;
+
+ function readJournal() {
+ if (existsSync(overflowPath)) { uncertain = true; reason ||= 'child spawn journal overflow or write failure'; }
+ let total = 0;
+ const files = readdirSync(journal.journalDirectory).filter(name => /^children-\d+\.jsonl$/u.test(name)).sort();
+ if (files.length > 10_000) { uncertain = true; reason ||= 'child spawn journal file limit exceeded'; return; }
+ for (const name of files) {
+ const file = join(journal.journalDirectory, name);
+ let size;
+ try { size = statSync(file).size; } catch { uncertain = true; reason ||= 'child spawn journal could not be inspected'; continue; }
+ total += size;
+ if (!Number.isSafeInteger(size) || size > 131_072 || total > 8 * 1024 * 1024) {
+ uncertain = true; reason ||= 'child spawn journal size limit exceeded'; continue;
+ }
+ const offset = offsets.get(name) ?? 0;
+ if (size < offset) { uncertain = true; reason ||= 'child spawn journal changed unexpectedly'; continue; }
+ if (size === offset) continue;
+ const length = size - offset;
+ const fd = openSync(file, 'r');
+ let text;
+ try {
+ const bytes = Buffer.alloc(length);
+ const read = readSync(fd, bytes, 0, length, offset);
+ if (read !== length) { uncertain = true; reason ||= 'child spawn journal read was incomplete'; continue; }
+ text = (partial.get(name) ?? '') + bytes.toString('utf8');
+ } finally { closeSync(fd); }
+ offsets.set(name, size);
+ const lines = text.split('\n');
+ partial.set(name, lines.pop() ?? '');
+ for (const line of lines) {
+ if (!line) continue;
+ if (line.length > 4_096) { uncertain = true; reason ||= 'child spawn journal record is oversized'; continue; }
+ let record;
+ try { record = JSON.parse(line); } catch { uncertain = true; reason ||= 'child spawn journal record is invalid'; continue; }
+ if (record.type === 'boot' && Number.isSafeInteger(record.pid) && record.pid > 0 && typeof record.instance === 'string') {
+ instancePids.set(record.instance, record.pid);
+ } else if (record.type === 'spawn' && Number.isSafeInteger(record.pid) && record.pid > 0
+ && Number.isSafeInteger(record.ppid) && record.ppid > 0
+ && typeof record.instance === 'string' && /^[a-f0-9]{64}$/u.test(record.commandSha256)) {
+ const childEvents = eventsByChild.get(record.pid) ?? [];
+ childEvents.push(record);
+ eventsByChild.set(record.pid, childEvents);
+ eventCount += 1;
+ if (eventCount > 100_000) { uncertain = true; reason ||= 'child spawn journal event limit exceeded'; return; }
+ } else { uncertain = true; reason ||= 'child spawn journal identity is invalid'; }
+ }
+ }
+ }
+
+ function observe() {
+ if (busy) return current;
+ busy = true;
+ try {
+ readJournal();
+ const rawCensus = processCensus();
+ if (!rawCensus) { censusFailure = true; return null; }
+ censusFailure = false;
+ const census = new Map([...rawCensus].map(([pid, row]) => [pid, processIdentity(row)]));
+ current = census;
+ for (const [pid, identity] of known) {
+ const row = current.get(pid);
+ if (!row || row.birth !== identity.birth) retired.add(`${pid}:${identity.birth}`);
+ else if (retired.has(`${pid}:${identity.birth}`)) {
+ uncertain = true; reason ||= 'a previously observed process identity reappeared';
+ }
+ }
+ const ownedPids = new Set();
+ for (const pid of roots) {
+ const row = current.get(pid);
+ if (!row) continue;
+ const prior = known.get(pid);
+ const launched = rootLaunchIdentities.get(pid);
+ if (prior && prior.birth !== row.birth) continue;
+ if (launched && launched.birth !== row.birth) continue;
+ if (!launched && row.ppid !== process.pid) continue;
+ if (!launched && row.pgid !== pid) continue;
+ if (retired.has(`${pid}:${row.birth}`)) { uncertain = true; reason ||= 'a retired process identity reappeared'; continue; }
+ if (!launched) rootLaunchIdentities.set(pid, row);
+ known.set(pid, { ...row, commandSha256: prior?.commandSha256 ?? '', root: true, group: pid });
+ ownedPids.add(pid);
+ }
+
+ for (const row of current.values()) {
+ for (const event of eventsByChild.get(row.pid) ?? []) {
+ const parentPid = instancePids.get(event.instance);
+ // A preload instance exists only in the private job environment. The receipt
+ // binds its child to that exact process instance even after the parent exits.
+ if (!parentPid || parentPid !== event.ppid) continue;
+ const prior = known.get(row.pid);
+ if (retired.has(`${row.pid}:${row.birth}`)) { uncertain = true; reason ||= 'a retired process identity reappeared'; continue; }
+ if (prior && prior.birth === row.birth) { ownedPids.add(row.pid); continue; }
+ if (!prior && baseline.get(row.pid)?.birth === row.birth) continue;
+ // A spawn receipt must be observed while its exact parent instance still owns it.
+ // A same-numbered PID first seen after reparenting is ambiguous and never adopted.
+ if (!prior && row.ppid !== event.ppid) { uncertain = true; reason ||= 'spawned process was first observed after reparenting'; continue; }
+ const parent = known.get(event.ppid);
+ const inheritedGroup = parent?.group ?? [...roots].find(rootPid => known.get(rootPid)?.group === row.pgid);
+ const group = row.pgid === row.pid ? row.pid : inheritedGroup;
+ if (group === undefined) { uncertain = true; reason ||= 'spawned process group has no owned parent'; continue; }
+ if (row.pgid === row.pid) detachedGroups.set(row.pid, row.birth);
+ known.set(row.pid, { ...row, commandSha256: event.commandSha256, root: false, group });
+ ownedPids.add(row.pid);
+ }
+ }
+
+ // Process ancestry captures non-Node children; journal receipts retain ownership after reparenting.
+ let changed = true;
+ while (changed) {
+ changed = false;
+ for (const row of current.values()) {
+ if (!ownedPids.has(row.ppid)) continue;
+ const prior = known.get(row.pid);
+ if (retired.has(`${row.pid}:${row.birth}`)) { uncertain = true; reason ||= 'a retired process identity reappeared'; continue; }
+ if (prior && prior.birth === row.birth) { ownedPids.add(row.pid); continue; }
+ if (!prior && baseline.get(row.pid)?.birth === row.birth) continue;
+ const parent = known.get(row.ppid);
+ const group = row.pgid === row.pid ? row.pid : parent?.group;
+ if (group === undefined) { uncertain = true; reason ||= 'descendant process group has no owned parent'; continue; }
+ if (row.pgid === row.pid) detachedGroups.set(row.pid, row.birth);
+ known.set(row.pid, { ...row, commandSha256: '', root: false, group });
+ ownedPids.add(row.pid); changed = true;
+ }
+ }
+ // Detached children establish a private process group; census every member even
+ // after the original launcher is reparented or exits.
+ for (const row of current.values()) {
+ const leaderStarted = detachedGroups.get(row.pgid);
+ if (!leaderStarted) continue;
+ const leader = current.get(row.pgid);
+ if (leader && leader.birth !== leaderStarted) {
+ uncertain = true; reason ||= 'detached process group identity was reused';
+ continue;
+ }
+ const prior = known.get(row.pid);
+ if (retired.has(`${row.pid}:${row.birth}`)) { uncertain = true; reason ||= 'a retired process identity reappeared'; continue; }
+ if (prior && prior.birth === row.birth) { ownedPids.add(row.pid); continue; }
+ if (!prior && baseline.get(row.pid)?.birth === row.birth) continue;
+ known.set(row.pid, { ...row, commandSha256: '', root: false, group: row.pgid });
+ ownedPids.add(row.pid);
+ }
+ // A recorded PGID does not prove an unseen member belongs to this job. Keep
+ // the lease fail-closed when a root group contains a process lacking identity evidence.
+ for (const rootPid of roots) {
+ for (const row of current.values()) {
+ if (row.pgid !== rootPid) continue;
+ const identity = known.get(row.pid);
+ if (identity?.birth === row.birth) continue;
+ if (baseline.get(row.pid)?.birth === row.birth) continue;
+ uncertain = true;
+ reason ||= 'owned process group contains an unidentified member';
+ }
+ }
+ if (known.size > 100_000) { uncertain = true; reason ||= 'owned process identity limit exceeded'; }
+ // Refresh live PGID/start data only when the PID still has the same start identity.
+ for (const pid of ownedPids) {
+ const row = current.get(pid);
+ const prior = known.get(pid);
+ if (row && prior?.birth === row.birth) Object.assign(prior, row);
+ }
+ return current;
+ } catch {
+ censusFailure = true; return null;
+ } finally { busy = false; }
+ }
+
+ function registerRoot(pid) {
+ if (!Number.isSafeInteger(pid) || pid < 1) return;
+ roots.add(pid);
+ // Bind the spawned leader while its actual parent is still this worker; later
+ // group membership alone is never sufficient to adopt an unknown process.
+ const census = processCensus();
+ const row = census?.get(pid);
+ if (row && row.ppid === process.pid && row.pgid === pid) rootLaunchIdentities.set(pid, processIdentity(row));
+ }
+
+ function liveDescendants() {
+ const active = [];
+ for (const [pid, identity] of known) {
+ if (identity.root) continue;
+ const row = current.get(pid);
+ if (row && row.birth === identity.birth && !retired.has(`${pid}:${identity.birth}`) && !/^Z/u.test(row.state)) active.push({ ...identity });
+ }
+ return active;
+ }
+
+ function signalOwnedGroup(pgid, signal) {
+ const census = observe();
+ if (!census || uncertain || censusFailure) return null;
+ const ownedMember = [...known].some(([pid, identity]) => {
+ const row = current.get(pid);
+ return row && row.pgid === pgid && row.birth === identity.birth && !/^Z/u.test(row.state);
+ });
+ if (!ownedMember) return false;
+ try { process.kill(-pgid, signal); }
+ catch (error) { if (error.code === 'ESRCH') return false; throw error; }
+ return true;
+ }
+
+ async function stopDescendantsLoop() {
+ // Retry through ambiguous censuses rather than releasing the host lease on an unproven drain.
+ for (;;) {
+ const census = observe();
+ if (!census) {
+ if (!warned) { process.stderr.write(`PULLBOARD_RUNNER_CLEANUP_UNVERIFIED ${workerId} ${reason}\n`); warned = true; }
+ await new Promise(resolvePause => setTimeout(resolvePause, 1_000));
+ continue;
+ }
+ if (uncertain) {
+ if (!warned) { process.stderr.write(`PULLBOARD_RUNNER_CLEANUP_UNVERIFIED ${workerId} ${reason}\n`); warned = true; }
+ await new Promise(resolvePause => setTimeout(resolvePause, 1_000));
+ continue;
+ }
+ if (censusFailure) { await new Promise(resolvePause => setTimeout(resolvePause, 250)); continue; }
+ const live = liveDescendants();
+ if (!live.length) return;
+ // Signal each confirmed owned process group once; use PID signals only with exact kernel identity.
+ const signaledGroups = new Set();
+ for (const identity of live) {
+ const row = current.get(identity.pid);
+ if (!row || row.birth !== identity.birth || retired.has(`${identity.pid}:${identity.birth}`) || /^Z/u.test(row.state)) continue;
+ const ownedGroup = identity.group;
+ if (Number.isSafeInteger(ownedGroup) && row.pgid === ownedGroup && !signaledGroups.has(ownedGroup)) {
+ const result = signalOwnedGroup(ownedGroup, 'SIGTERM');
+ if (result === null) { censusFailure = true; break; }
+ if (result) signaledGroups.add(ownedGroup);
+ continue;
+ }
+ if (!identity.exact) { uncertain = true; reason ||= 'descendant lacks a safe process-group identity'; break; }
+ try { process.kill(identity.pid, 'SIGTERM'); }
+ catch (error) { if (error.code !== 'ESRCH') { uncertain = true; reason ||= 'owned descendant could not be stopped safely'; } }
+ }
+ const deadline = Date.now() + 2_000;
+ while (Date.now() < deadline) {
+ await new Promise(resolvePause => setTimeout(resolvePause, 50));
+ if (!observe()) break;
+ if (!liveDescendants().length) break;
+ }
+ if (!current || !liveDescendants().length) continue;
+ const killedGroups = new Set();
+ for (const identity of liveDescendants()) {
+ const row = current.get(identity.pid);
+ if (!row || row.birth !== identity.birth || retired.has(`${identity.pid}:${identity.birth}`) || /^Z/u.test(row.state)) continue;
+ const ownedGroup = identity.group;
+ if (Number.isSafeInteger(ownedGroup) && row.pgid === ownedGroup && !killedGroups.has(ownedGroup)) {
+ const result = signalOwnedGroup(ownedGroup, 'SIGKILL');
+ if (result === null) { censusFailure = true; break; }
+ if (result) killedGroups.add(ownedGroup);
+ continue;
+ }
+ if (!identity.exact) { uncertain = true; reason ||= 'descendant lacks a safe process-group identity'; break; }
+ try { process.kill(identity.pid, 'SIGKILL'); }
+ catch (error) { if (error.code !== 'ESRCH') { uncertain = true; reason ||= 'owned descendant could not be killed safely'; } }
+ }
+ await new Promise(resolvePause => setTimeout(resolvePause, 100));
+ }
+ }
+
+ function stopDescendants() {
+ if (!stoppingPromise) {
+ stoppingPromise = stopDescendantsLoop().finally(() => { stoppingPromise = null; });
+ }
+ return stoppingPromise;
+ }
+
+ async function verifyAfterGroups() {
+ for (;;) {
+ const census = observe();
+ if (census && !uncertain && !censusFailure) {
+ const liveRoots = [...roots].some(pid => {
+ const row = current.get(pid);
+ const knownRoot = known.get(pid);
+ return row && knownRoot?.birth === row.birth && !/^Z/u.test(row.state);
+ });
+ if (!liveRoots && !liveDescendants().length) return;
+ }
+ if (!warned) { process.stderr.write(`PULLBOARD_RUNNER_CLEANUP_UNVERIFIED ${workerId} ${reason || 'owned process identity remains live'}\n`); warned = true; }
+ await new Promise(resolvePause => setTimeout(resolvePause, 1_000));
+ }
+ }
+
+ timer = setInterval(() => { if (!busy) observe(); }, 250);
+ timer.unref();
+ return {
+ nodeOptions: journal.nodeOptions,
+ registerRoot,
+ stopDescendants,
+ /** Revalidate a process group immediately before signaling; null means census ambiguity. */
+ signalOwnedGroup,
+ verifyAfterGroups,
+ stopMonitoring() { clearInterval(timer); },
+ };
+}
+
/** Stop and fully drain one owned process group before its gate lease can be released. */
-function drainOwned(record, terminate = false) {
+function drainOwned(record, terminate = false, tracker = activeDescendantTracker) {
if (!record) return Promise.resolve();
record.drainPromise ??= (async () => {
- if (terminate) await stopOwnedGroup(record.pid, record.closed);
+ if (terminate) await stopOwnedGroup(record.pid, record.closed, tracker);
else {
await record.closed;
- await stopOwnedGroup(record.pid, record.closed);
+ await stopOwnedGroup(record.pid, record.closed, tracker);
}
ownedChildren.delete(record.child);
})();
@@ -192,7 +618,11 @@ function installSignalCustody() {
rejectPendingFrame?.(new Error('runner transport was lost'));
clearInterval(heartbeatTimer);
const active = [...ownedChildren.values()];
- transportDrain = Promise.all(active.map(record => drainOwned(record, true)));
+ transportDrain = (async () => {
+ await activeDescendantTracker?.stopDescendants();
+ await Promise.all(active.map(record => drainOwned(record, true)));
+ await activeDescendantTracker?.verifyAfterGroups();
+ })();
transportDrain.catch(() => {});
};
transportDrop = disconnected;
@@ -274,31 +704,33 @@ async function checkoutHistory(api, runnerRoot, root, packFile, spec, env) {
const build = mkdtempSync(join(repositories, `.repo-${spec.repoId}-`));
const staged = join(build, 'cache.git');
try {
- let cloned = false;
- if (spec.origin) {
- const clone = spawnOwned('git', ['clone', '--bare', '--no-hardlinks', '--origin=origin', spec.origin, staged], {
- cwd: build, env, stdio: ['ignore', 'ignore', 'ignore'],
- });
- const result = await clone.closed;
- await drainOwned(clone);
- cloned = !result.error && result.code === 0 && !result.signal;
- if (cloned) {
- try {
- cloned = await git(staged, ['rev-parse', '--is-bare-repository'], env) === 'true'
- && await git(staged, ['rev-parse', '--show-object-format'], env) === (spec.commit.length === 64 ? 'sha256' : 'sha1')
- && !existsSync(join(staged, 'shallow'))
- && !existsSync(join(staged, 'objects', 'info', 'alternates'));
- } catch { cloned = false; }
- }
- if (!cloned) rmSync(staged, { recursive: true, force: true });
- }
- if (!cloned) {
+ const initialize = async () => {
const initialized = spawnOwned('git', ['init', '--bare', `--object-format=${spec.commit.length === 64 ? 'sha256' : 'sha1'}`, staged], {
cwd: build, env, stdio: ['ignore', 'ignore', 'ignore'],
});
const result = await initialized.closed;
await drainOwned(initialized);
if (result.error || result.code !== 0 || result.signal) throw new Error('source history cache could not be initialized');
+ };
+ await initialize();
+ if (spec.origin && spec.originBase) {
+ let seeded = false;
+ try {
+ const fetch = spawnOwned('git', ['-c', 'protocol.version=2', 'fetch', '--no-tags', '--no-recurse-submodules', spec.origin, spec.originBase], {
+ cwd: staged, env, stdio: ['ignore', 'ignore', 'ignore'],
+ });
+ const result = await fetch.closed;
+ await drainOwned(fetch);
+ seeded = !result.error && result.code === 0 && !result.signal
+ && await git(staged, ['cat-file', '-t', spec.originBase], env) === 'commit'
+ && Number(await git(staged, ['rev-list', '--count', spec.originBase], env)) > 0
+ && !existsSync(join(staged, 'shallow'));
+ if (seeded) await git(staged, ['update-ref', `refs/pullboard/published/${spec.originBase}`, spec.originBase], env);
+ } catch { seeded = false; }
+ if (!seeded) {
+ rmSync(staged, { recursive: true, force: true });
+ await initialize();
+ }
}
renameSync(staged, cache);
} finally { rmSync(build, { recursive: true, force: true }); }
@@ -308,15 +740,14 @@ async function checkoutHistory(api, runnerRoot, root, packFile, spec, env) {
|| existsSync(join(cache, 'shallow')) || existsSync(join(cache, 'objects', 'info', 'alternates'))) {
throw new Error('source history cache has an incompatible format');
}
- const refLines = await git(cache, ['for-each-ref', '--format=%(refname) %(objectname)', 'refs/heads', 'refs/pullboard/candidates'], env);
+ const refLines = await git(cache, ['for-each-ref', '--format=%(refname) %(objectname)', 'refs/pullboard/candidates', 'refs/pullboard/published'], env);
const tips = [];
if (refLines) for (const line of refLines.split(/\r?\n/u)) {
- const split = /^(refs\/(?:heads|pullboard\/candidates)\/.+) ([a-f0-9]{40,64})$/u.exec(line);
+ const split = /^(refs\/pullboard\/(?:candidates|published)\/.+) ([a-f0-9]{40,64})$/u.exec(line);
if (!split || split[2].length !== spec.commit.length) {
throw new Error('source history cache contains an invalid candidate ref');
}
- if (split[1].startsWith('refs/pullboard/candidates/')
- && split[1].slice('refs/pullboard/candidates/'.length) !== split[2]) {
+ if (split[1].slice(split[1].lastIndexOf('/') + 1) !== split[2]) {
throw new Error('source history cache contains an invalid candidate ref');
}
if (await git(cache, ['cat-file', '-t', split[2]], env) !== 'commit') {
@@ -348,6 +779,7 @@ async function checkoutHistory(api, runnerRoot, root, packFile, spec, env) {
}
const historyCount = Number(await git(cache, ['rev-list', '--count', spec.commit], env));
if (!Number.isSafeInteger(historyCount) || historyCount < 1) throw new Error('source history is incomplete');
+ if (spec.originBase) await git(cache, ['merge-base', '--is-ancestor', spec.originBase, spec.commit], env);
const closure = new Set((await git(cache, ['rev-list', '--objects', spec.commit], env)).split(/\r?\n/u)
.map(line => line.match(/^([a-f0-9]{40,64})(?:\s|$)/u)?.[1]).filter(Boolean));
closure.add(spec.commit);
@@ -380,7 +812,7 @@ async function checkoutHistory(api, runnerRoot, root, packFile, spec, env) {
}
/** Install committed npm dependencies through an isolated content-addressed cache, refusing unknown lock managers. */
-async function installDependencies(api, root, runnerRoot, privateHome, env, commitTree) {
+async function installDependencies(root, runnerRoot, env, tracker) {
const packageFile = join(root, 'package.json');
if (!existsSync(packageFile)) return;
const packageText = readFileSync(packageFile, 'utf8');
@@ -395,52 +827,20 @@ async function installDependencies(api, root, runnerRoot, privateHome, env, comm
}
return;
}
- const lockText = readFileSync(lockFile, 'utf8');
- const key = createHash('sha256').update(packageText).update('\0').update(lockText).update('\0')
- .update(process.versions.modules).update('\0').update(process.platform).update('\0').update(process.arch).update('\0').update(commitTree).digest('hex');
const cacheRoot = join(runnerRoot, 'cache', 'npm');
- const installCache = join(cacheRoot, 'installed');
const contentCache = join(cacheRoot, 'content');
- const cache = join(installCache, key);
- mkdirSync(installCache, { recursive: true, mode: 0o700 });
mkdirSync(contentCache, { recursive: true, mode: 0o700 });
- chmodSync(cacheRoot, 0o700); chmodSync(installCache, 0o700); chmodSync(contentCache, 0o700);
- const previousMachineHome = process.env.PULLBOARD_MACHINE_HOME;
- const cachePool = join(runnerRoot, 'cache', 'resource-pool');
- let releaseCache = null;
- try {
- if (!existsSync(cache)) {
- const lease = await acquireResourceApi(api, {
- name: `npm-cache-${key}`, capacity: 1, scope: 'machine', root: runnerRoot,
- repo: runnerRoot, agent: 'pullboard-runner-cache', kind: 'npm-cache',
- onWait: () => assertTransportLive(),
- }, cachePool);
- releaseCache = lease.release;
- }
- if (!existsSync(cache)) {
- const build = mkdtempSync(join(installCache, `${key}.build-`));
- try {
- rmSync(join(root, 'node_modules'), { recursive: true, force: true });
- const npm = spawnOwned('npm', ['ci', '--cache', contentCache], {
- cwd: root, env, stdio: ['ignore', 'ignore', 'ignore'],
- });
- const result = await npm.closed;
- await drainOwned(npm);
- if (result.error || result.code !== 0 || result.signal) throw new Error('committed npm dependencies could not be installed');
- mkdirSync(join(root, 'node_modules'), { recursive: true, mode: 0o700 });
- cpSync(join(root, 'node_modules'), join(build, 'node_modules'), { recursive: true, errorOnExist: true, verbatimSymlinks: true });
- renameSync(build, cache);
- } finally { rmSync(build, { recursive: true, force: true }); }
- }
- const from = join(cache, 'node_modules');
- if (!existsSync(join(root, 'node_modules'))) cpSync(from, join(root, 'node_modules'), { recursive: true, errorOnExist: true, verbatimSymlinks: true });
- } finally {
- try { releaseCache?.(); }
- finally {
- if (previousMachineHome === undefined) delete process.env.PULLBOARD_MACHINE_HOME;
- else process.env.PULLBOARD_MACHINE_HOME = previousMachineHome;
- }
- }
+ chmodSync(cacheRoot, 0o700); chmodSync(contentCache, 0o700);
+ // node_modules is job-local because package lifecycle scripts may create sibling artifacts.
+ // Reuse only npm's content-addressed download cache, never a prior job's installed tree.
+ rmSync(join(root, 'node_modules'), { recursive: true, force: true });
+ const npm = spawnOwned('npm', ['ci', '--cache', contentCache], {
+ cwd: root, env, stdio: ['ignore', 'ignore', 'ignore'],
+ });
+ const result = await npm.closed;
+ await tracker.stopDescendants();
+ await drainOwned(npm);
+ if (result.error || result.code !== 0 || result.signal) throw new Error('committed npm dependencies could not be installed');
}
/** Wait until all bytes written to stdout have passed through the stream before publishing a receipt. */
@@ -464,30 +864,33 @@ function outputSink() {
}
/** Stop only the detached command process group owned by this worker, then await its close event. */
-async function stopOwnedGroup(pid, closed) {
+async function stopOwnedGroup(pid, closed, tracker) {
if (!pid) return;
- try { process.kill(-pid, 'SIGTERM'); } catch (error) { if (error.code !== 'ESRCH') throw error; }
+ const signal = async type => {
+ for (;;) {
+ const sent = tracker?.signalOwnedGroup(pid, type) ?? false;
+ if (sent === true || sent === false) return sent;
+ await new Promise(resolvePause => setTimeout(resolvePause, 250));
+ }
+ };
+ await signal('SIGTERM');
// Give the whole owned group two seconds to handle TERM, even if its leader exits first.
const graceUntil = Date.now() + 2_000;
- let alive = true;
- while (alive && Date.now() < graceUntil) {
- try { process.kill(-pid, 0); }
- catch (error) { if (error.code === 'ESRCH') { alive = false; break; } throw error; }
+ while (Date.now() < graceUntil) {
+ const sent = await signal('SIGTERM');
+ if (!sent) break;
await new Promise(resolvePause => setTimeout(resolvePause, 25));
}
- if (alive) {
- try { process.kill(-pid, 'SIGKILL'); } catch (error) { if (error.code !== 'ESRCH') throw error; }
- }
for (;;) {
- try { process.kill(-pid, 0); }
- catch (error) { if (error.code === 'ESRCH') break; throw error; }
+ const sent = await signal('SIGKILL');
+ if (!sent) break;
await new Promise(resolvePause => setTimeout(resolvePause, 50));
}
await closed;
}
/** Run the exact requested command in its isolated checkout, retaining raw output and real test exit status. */
-async function runCommand(spec, root, env, sink) {
+async function runCommand(spec, root, env, sink, tracker) {
let shell = '/bin/sh';
let args = ['-c', spec.command];
if (spec.pipefail) {
@@ -509,6 +912,7 @@ async function runCommand(spec, root, env, sink) {
forward(child.stdout); forward(child.stderr);
const result = await closed;
await writes;
+ await tracker.stopDescendants();
await drainOwned(owned);
if (transportDrain) await transportDrain;
if (outputError) throw outputError;
@@ -543,6 +947,7 @@ async function main() {
const sink = outputSink();
let api;
let lease = null;
+ let tracker = null;
let runDirectory;
let final = { code: 1, signal: null, root: '' };
try {
@@ -584,16 +989,24 @@ async function main() {
onWait: () => assertTransportLive(),
}, machineHomePath);
const canonicalMachineHome = machineHomePath;
- const env = scopedEnvironment(privateHome, temporary, canonicalMachineHome, lease, api);
+ tracker = createDescendantTracker(runDirectory);
+ activeDescendantTracker = tracker;
+ const env = scopedEnvironment(privateHome, temporary, canonicalMachineHome, lease, api, tracker.nodeOptions);
await checkoutHistory(api, runnerRoot, root, packFile, spec, env);
- await installDependencies(api, root, runnerRoot, privateHome, env, spec.tree);
- final = { ...(await runCommand(spec, root, env, sink)), root };
+ await installDependencies(root, runnerRoot, env, tracker);
+ final = { ...(await runCommand(spec, root, env, sink, tracker)), root };
} catch (error) {
const message = safeSetupMessage(error);
if (!transportLost) await sink.write(`${message}\n`);
final = { code: 1, signal: transportLost ? 'SIGHUP' : null, error: message, root: '' };
} finally {
+ if (tracker) await tracker.stopDescendants();
await drainAllOwned();
+ if (tracker) {
+ await tracker.verifyAfterGroups();
+ tracker.stopMonitoring();
+ activeDescendantTracker = null;
+ }
if (lease) {
try { lease.release(); } catch { /* Retaining a lease on cleanup error is safer than speculative deletion. */ }
}
diff --git a/src/runners.js b/src/runners.js
index de625b49..517be939 100644
--- a/src/runners.js
+++ b/src/runners.js
@@ -11,7 +11,8 @@ import { blockedPaths, secretsIn } from './hooks.js';
import { cleanGitEnvironment, headCommit, headTree, isClean, repoInfo, untracked } from './git.js';
import { Refused } from './refused.js';
-const MAX_OUTPUT_BYTES = 1024 ** 3;
+// Budget: 64 MiB bounds worst-case JSON bridge escaping below Node string limits.
+const MAX_OUTPUT_BYTES = 64 * 1024 ** 2;
const MAX_BLOB_BYTES = 8 * 1024 ** 2;
const TOOL_ROOT = fileURLToPath(new URL('../', import.meta.url));
const RUNTIME_NAMES = ['resources.js', 'git.js', 'machine-home.js', 'refused.js'];
@@ -85,7 +86,7 @@ function sourceObjects(root, source) {
if (secretsIn(commit.split('\n').map((text, index) => ({ path: 'commit', line: index + 1, text }))).length) {
throw new Refused('RUNNER_SECRET', 'the commit metadata contains a possible secret; keep this run local and correct the metadata');
}
-
+ return config.protect;
}
/** Reject blocked historical paths as well as current ones before an object pack crosses SSH. */
@@ -93,6 +94,27 @@ function protectedHistoryPath(path, protect) {
return blockedPaths([path], protect).length || /(?:^|\/)board\.sqlite(?:-(?:wal|shm))?$/u.test(path);
}
+/** Apply current protection rules to all selected historical names before any anonymous cache seed. */
+function protectHistory(root, source, protect) {
+ const paths = [...new Set(sourceGit(root, ['log', '--format=', '--name-only', '-z', '--no-renames', '--root', '-m', '--full-history', source.commit])
+ .split('\0').filter(Boolean))];
+ if (paths.some(path => protectedHistoryPath(path, protect))) {
+ throw new Refused('RUNNER_SECRET', 'selected history includes a blocked private path; keep this run local or remove that private history');
+ }
+}
+
+/** Select a locally known published ancestor, never an anonymous origin's unchecked latest tip. */
+function originAncestor(root, source) {
+ const tip = sourceGit(root, ['for-each-ref', '--format=%(objectname)', 'refs/remotes/origin']).split('\n')
+ .find(value => /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(value));
+ if (!tip) return undefined;
+ const result = spawnSync('git', ['--no-replace-objects', 'merge-base', source.commit, tip], {
+ cwd: root, env: cleanGitEnvironment(), encoding: 'utf8', maxBuffer: 4096,
+ });
+ const base = result.stdout?.trim();
+ return result.status === 0 && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(base) ? base : undefined;
+}
+
/** Read one exact cat-file record without loading a repository's history into memory. */
function objectRecord(descriptor) {
const header = [];
@@ -253,12 +275,15 @@ function requestFor(root, command, { runner, source, browser = false, pipefail =
if (secretsIn(command.split('\n').map((text, index) => ({ path: 'run command', line: index + 1, text }))).length) {
throw new Refused('RUNNER_SECRET', 'the run command contains a possible secret; use a command that does not transfer credentials');
}
- sourceObjects(root, current);
+ const protect = sourceObjects(root, current);
+ protectHistory(root, current, protect);
+ const origin = anonymousOrigin(root);
+ const originBase = origin ? originAncestor(root, current) : undefined;
const repoId = createHash('sha256').update(realpathSync(repoInfo(root).commonDir)).digest('hex');
const directory = mkdtempSync(join(tmpdir(), 'pullboard-runner-send-'));
try {
const { worker, tooling, runtime } = trustedTooling();
- const spec = { version: 1, id: randomUUID(), repoId, origin: anonymousOrigin(root), runtime, tooling, ...current, command, pipefail, slots: runner.slots,
+ const spec = { version: 1, id: randomUUID(), repoId, ...(originBase ? { origin, originBase } : {}), runtime, tooling, ...current, command, pipefail, slots: runner.slots,
browser: runner.browser, browserRequired: browser, landing: metadata.landing === true,
itemCheck: metadata.itemCheck === true, diagnostic: metadata.diagnostic === true,
item: String(metadata.item ?? ''), kind: String(metadata.kind ?? ''), ...(runner.root ? { root: runner.root } : {}) };
@@ -304,10 +329,17 @@ export function runOnRunner(root, command, options) {
const script = `import { runOnRunnerAsync } from ${JSON.stringify(import.meta.url)};
let input=''; for await (const chunk of process.stdin) input+=chunk;
const request=JSON.parse(input);
-try { process.stdout.write(JSON.stringify({result:await runOnRunnerAsync(request.root,request.command,request.options)})); }
-catch(error) { process.stdout.write(JSON.stringify({error:{name:error.name,code:error.code,message:error.message,host:error.host}})); process.exitCode=1; }`;
+const canceled=new AbortController();
+const abort=()=>canceled.abort();
+process.on('SIGTERM',abort); process.on('SIGHUP',abort); process.stdout.on('error',abort);
+// Budget: check actual parent identity every second while the negotiated SSH transport is active.
+const parentWatch=setInterval(()=>{if(process.ppid!==request.parentPid)abort();},1000);
+if(process.ppid!==request.parentPid)abort();
+try { process.stdout.write(JSON.stringify({result:await runOnRunnerAsync(request.root,request.command,{...request.options,signal:canceled.signal})})); }
+catch(error) { process.stdout.write(JSON.stringify({error:{name:error.name,code:error.code,message:error.message,host:error.host}})); process.exitCode=1; }
+finally {clearInterval(parentWatch);}`;
const child = spawnSync(process.execPath, ['--input-type=module', '-e', script], {
- cwd: root, input: JSON.stringify({ root, command, options }), encoding: 'utf8', maxBuffer: MAX_OUTPUT_BYTES * 2,
+ cwd: root, input: JSON.stringify({ root, command, options, parentPid: process.pid }), encoding: 'utf8', maxBuffer: MAX_OUTPUT_BYTES * 6 + 1024 ** 2,
stdio: ['pipe', 'pipe', 'pipe'],
});
let reply;
@@ -322,15 +354,21 @@ catch(error) { process.stdout.write(JSON.stringify({error:{name:error.name,code:
/** Negotiate missing history objects while the remote cache lease stays held in one SSH session. */
export async function runOnRunnerAsync(root, command, options) {
+ if (options.signal?.aborted) throw new RunnerDropped(options.runner.host);
const request = requestFor(root, command, options);
+ let removeAbort = () => {};
try {
const child = spawn('ssh', request.args, { env: request.env, stdio: ['pipe', 'pipe', 'pipe'] });
const output = [], diagnostics = [];
let bytes = 0, error, control = '', requested = false, transfer = null;
+ const abort = () => { error ??= new Error('runner transport canceled'); child.stdin.destroy(); child.kill('SIGTERM'); };
+ options.signal?.addEventListener('abort', abort, { once: true });
+ removeAbort = () => options.signal?.removeEventListener('abort', abort);
+ if (options.signal?.aborted) abort();
/** Bound both protocol streams before retaining a complete result. */
const capture = (target, chunk) => {
bytes += chunk.length;
- if (bytes > MAX_OUTPUT_BYTES) { error = new Error('runner output exceeded limit'); child.kill(); }
+ if (bytes > MAX_OUTPUT_BYTES) { error = new Refused('RUNNER_OUTPUT_LIMIT', 'runner output exceeded 64 MiB; reduce command output or keep this run local'); child.kill(); }
else target.push(chunk);
};
child.stdout.on('data', chunk => capture(output, chunk));
@@ -363,5 +401,5 @@ export async function runOnRunnerAsync(root, command, options) {
if (transfer) await transfer;
if (error instanceof Refused) throw error;
return resultFrom(request, { status, error, stdout: Buffer.concat(output), stderr: Buffer.concat(diagnostics) });
- } finally { request.cleanup(); }
+ } finally { removeAbort(); request.cleanup(); }
}
diff --git a/test/fixtures/resources-pre-runners.js b/test/fixtures/resources-pre-runners.js
new file mode 100644
index 00000000..bfcb177b
--- /dev/null
+++ b/test/fixtures/resources-pre-runners.js
@@ -0,0 +1,386 @@
+/** Test-only frozen resource API from baseline 3762af1caf428ac818a49d4b78345648ee89dbfc; only relative production imports are redirected. */
+/** Machine and repository queues persist leases; landings go first, then eligible waiters in arrival order [Q1,Q2,Q3]. */
+import { mkdirSync, realpathSync } from 'node:fs';
+import { execFileSync } from 'node:child_process';
+import { basename, dirname, join, resolve } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { DatabaseSync } from 'node:sqlite';
+import { repoInfo } from '../../src/git.js';
+import { machineHome } from '../../src/machine-home.js';
+import { Refused } from '../../src/refused.js';
+
+const LEASE_MS = 20_000;
+const HEARTBEAT_MS = 3_000;
+const POLL_MS = 40;
+const PROCESS_IDENTITY_CACHE_MS = 3_000;
+const processIdentities = new Map();
+
+/** Mark child commands whose parent already owns a machine gate slot. */
+export const GATE_SLOT_HELD_ENV = 'PULLBOARD_GATE_SLOT_HELD';
+export const GATE_SLOT_POOL_ENV = 'PULLBOARD_GATE_SLOT_POOL';
+export const GATE_SLOT_TOKEN_ENV = 'PULLBOARD_GATE_SLOT_TOKEN';
+export const BROWSER_SLOT_HELD_ENV = 'PULLBOARD_BROWSER_SLOT_HELD';
+
+/** Build child markers that identify the exact machine queue lease and its browser capacity. */
+export function gateSlotEnvironment(lease) {
+ if (!lease || lease.name !== 'gate' || lease.scope !== 'machine' || typeof lease.pool !== 'string' || typeof lease.token !== 'string') {
+ throw new Refused('GATE_SLOT_LEASE_REQUIRED', 'pass the live machine gate lease when starting a child test process');
+ }
+ return {
+ [GATE_SLOT_HELD_ENV]: '1',
+ [GATE_SLOT_POOL_ENV]: lease.pool,
+ [GATE_SLOT_TOKEN_ENV]: lease.token,
+ [BROWSER_SLOT_HELD_ENV]: lease.browser ? '1' : '',
+ };
+}
+
+/** Resolve the local database for the requested scope. */
+function databaseFile(scope, root) {
+ if (scope === 'board') throw new Refused('BOARD_SCOPE_UNAVAILABLE', 'board-scoped resources need the relay; run pullboard relay on');
+ if (scope === 'machine') return machineResourceFile();
+ if (scope === 'repo') return join(repoInfo(root).commonDir, 'pullboard', 'resources.sqlite');
+ throw new Refused('BAD_RESOURCE_SCOPE', `unknown resource scope "${scope}"; use machine or repo`);
+}
+
+/** Resolve the database path for the machine-wide resource pool. */
+function machineResourceFile() {
+ return join(machineHome(), 'resources.sqlite');
+}
+
+/** Canonicalize an absolute resource path without creating a missing foreign pool. */
+function canonicalResourceFile(file) {
+ let candidate = resolve(file);
+ const missing = [];
+ while (true) {
+ try {
+ return resolve(realpathSync(candidate), ...missing);
+ } catch (error) {
+ if (error.code !== 'ENOENT') throw error;
+ const parent = dirname(candidate);
+ if (parent === candidate) throw error;
+ missing.unshift(basename(candidate));
+ candidate = parent;
+ }
+ }
+}
+
+/** Open and initialize the small durable queue database. */
+function open(file) {
+ mkdirSync(dirname(file), { recursive: true });
+ const db = new DatabaseSync(file);
+ db.exec('PRAGMA busy_timeout = 10000');
+ let transaction = false;
+ try {
+ db.exec('BEGIN IMMEDIATE');
+ transaction = true;
+ db.exec(`CREATE TABLE IF NOT EXISTS resource (name TEXT PRIMARY KEY, capacity INTEGER NOT NULL);
+ CREATE TABLE IF NOT EXISTS holder (token TEXT PRIMARY KEY, name TEXT NOT NULL, pid INTEGER NOT NULL, started TEXT NOT NULL DEFAULT '', agent TEXT NOT NULL, repo TEXT NOT NULL, since TEXT NOT NULL, heartbeat INTEGER NOT NULL, landing INTEGER NOT NULL DEFAULT 0, item_check INTEGER NOT NULL DEFAULT 0, browser INTEGER NOT NULL DEFAULT 0, item TEXT NOT NULL DEFAULT '', kind TEXT NOT NULL DEFAULT '');
+ CREATE INDEX IF NOT EXISTS holder_name ON holder(name);
+ CREATE TABLE IF NOT EXISTS waiter (ticket INTEGER PRIMARY KEY AUTOINCREMENT, token TEXT UNIQUE NOT NULL, name TEXT NOT NULL, pid INTEGER NOT NULL, started TEXT NOT NULL DEFAULT '', agent TEXT NOT NULL, repo TEXT NOT NULL, since TEXT NOT NULL, heartbeat INTEGER NOT NULL, landing INTEGER NOT NULL DEFAULT 0, item_check INTEGER NOT NULL DEFAULT 0, browser INTEGER NOT NULL DEFAULT 0, item TEXT NOT NULL DEFAULT '', kind TEXT NOT NULL DEFAULT '');
+ CREATE INDEX IF NOT EXISTS waiter_name_ticket ON waiter(name, ticket);`);
+ for (const table of ['holder', 'waiter']) {
+ const columns = db.prepare(`PRAGMA table_info(${table})`).all().map(({ name }) => name);
+ if (!columns.includes('started')) db.exec(`ALTER TABLE ${table} ADD COLUMN started TEXT NOT NULL DEFAULT ''`);
+ if (!columns.includes('landing')) db.exec(`ALTER TABLE ${table} ADD COLUMN landing INTEGER NOT NULL DEFAULT 0`);
+ if (!columns.includes('item_check')) db.exec(`ALTER TABLE ${table} ADD COLUMN item_check INTEGER NOT NULL DEFAULT 0`);
+ if (!columns.includes('diagnostic')) db.exec(`ALTER TABLE ${table} ADD COLUMN diagnostic INTEGER NOT NULL DEFAULT 0`);
+ if (!columns.includes('browser')) db.exec(`ALTER TABLE ${table} ADD COLUMN browser INTEGER NOT NULL DEFAULT 0`);
+ if (!columns.includes('item')) db.exec(`ALTER TABLE ${table} ADD COLUMN item TEXT NOT NULL DEFAULT ''`);
+ if (!columns.includes('kind')) db.exec(`ALTER TABLE ${table} ADD COLUMN kind TEXT NOT NULL DEFAULT ''`);
+ }
+ db.exec('COMMIT');
+ transaction = false;
+ } catch (error) {
+ if (transaction) {
+ try { db.exec('ROLLBACK'); } catch { /* Preserve the migration error. */ }
+ }
+ db.close();
+ throw error;
+ }
+ return db;
+}
+
+/** Check whether the operating system still recognizes this process ID. */
+function alive(pid) {
+ try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; }
+}
+
+/** Read a stable OS process identity; an unreadable identity is unknown, not proof of death. */
+function processIdentity(pid) {
+ const cached = processIdentities.get(pid);
+ if (cached && Date.now() - cached.checkedAt < PROCESS_IDENTITY_CACHE_MS) return cached.identity;
+ let identity = null;
+ try {
+ const output = execFileSync('/bin/ps', ['-o', 'lstart=', '-o', 'stat=', '-p', String(pid)], {
+ encoding: 'utf8',
+ env: { ...process.env, TZ: 'UTC', LC_ALL: 'C', LANG: 'C' },
+ stdio: ['ignore', 'pipe', 'ignore'],
+ }).trim();
+ const fields = output.split(/\s+/u);
+ const state = fields.pop();
+ if (fields.length) identity = { started: fields.join(' '), zombie: state?.startsWith('Z') ?? false };
+ } catch { /* A live PID remains authoritative when the OS identity utility is unavailable. */ }
+ processIdentities.set(pid, { identity, checkedAt: Date.now() });
+ if (processIdentities.size > 1024) {
+ for (const [cachedPid, entry] of processIdentities) {
+ if (Date.now() - entry.checkedAt >= PROCESS_IDENTITY_CACHE_MS) processIdentities.delete(cachedPid);
+ }
+ }
+ return identity;
+}
+
+/** Read the start identity to store with a lease when the OS can provide it. */
+function processStarted(pid) {
+ return processIdentity(pid)?.started ?? '';
+}
+
+/** Confirm that a live PID still belongs to the process recorded in the lease. */
+function sameProcess(pid, started) {
+ if (!alive(pid)) return false;
+ const identity = processIdentity(pid);
+ if (!identity) return true;
+ if (identity.zombie) return false;
+ return !started || identity.started === started;
+}
+
+/** Return the Git root for display when the resource caller is inside a repository. */
+function repoRoot(root) {
+ try { return repoInfo(root).root; } catch { return ''; }
+}
+
+/** Run a short serialized database update and discard dead or expired leases. */
+function update(db, action) {
+ db.exec('BEGIN IMMEDIATE');
+ try {
+ const cutoff = Date.now() - LEASE_MS;
+ for (const row of db.prepare('SELECT token, pid, started, heartbeat FROM holder').all()) {
+ if (!alive(row.pid) || (row.heartbeat < cutoff && !sameProcess(row.pid, row.started))) {
+ db.prepare('DELETE FROM holder WHERE token = ?').run(row.token);
+ }
+ }
+ for (const row of db.prepare('SELECT token, pid, started, heartbeat FROM waiter').all()) {
+ if (!alive(row.pid) || (row.heartbeat < cutoff && !sameProcess(row.pid, row.started))) {
+ db.prepare('DELETE FROM waiter WHERE token = ?').run(row.token);
+ }
+ }
+ const result = action();
+ db.exec('COMMIT');
+ return result;
+ } catch (error) {
+ db.exec('ROLLBACK');
+ throw error;
+ }
+}
+
+/** Current holders and the landing-first line, then every other kind in arrival order. */
+function snapshot(db, name) {
+ /** Preserve older public entries while naming diagnostics as a distinct queue class. */
+ const project = ({ diagnostic, browser, item, kind, ...entry }) => ({ ...entry, landing: entry.landing === 1,
+ itemCheck: entry.itemCheck === 1 && diagnostic !== 1, ...(diagnostic === 1 ? { diagnostic: true } : {}),
+ ...(browser === 1 ? { browser: true } : {}), ...(item ? { item } : {}), ...(kind ? { kind } : {}) });
+ // Browser is an additional capability on a gate lease, not a second partially held row.
+ const where = name === 'browser' ? 'name = ? AND browser = 1' : 'name = ?';
+ const sourceName = name === 'browser' ? 'gate' : name;
+ const holders = db.prepare(`SELECT agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, item, kind FROM holder WHERE ${where} ORDER BY since, token`).all(sourceName).map(project);
+ const line = db.prepare(`SELECT agent, repo, since, landing, item_check AS itemCheck, diagnostic, browser, item, kind FROM waiter WHERE ${where} ORDER BY landing DESC, ticket`).all(sourceName).map(project);
+ return { holders, line };
+}
+
+/** Count reported or admissible queue position separately so blocked work cannot distort the visible line. */
+function waiterPosition(db, name, ticket, { eligibleOnly = false } = {}) {
+ const queueName = name === 'browser' ? 'gate' : name;
+ const waiters = db.prepare('SELECT ticket, pid, agent, repo, landing, item_check AS itemCheck, browser FROM waiter WHERE name = ? ORDER BY ticket').all(queueName);
+ const holders = db.prepare('SELECT pid, agent, repo FROM holder WHERE name = ?').all(queueName);
+ const browserBusy = db.prepare("SELECT COUNT(*) AS count FROM holder WHERE name = 'gate' AND browser = 1").get().count > 0;
+ /** A live process owns its leases even if it changes descriptive agent or repository labels. */
+ const holdsSlot = (waiter) => holders.some((holder) => holder.pid === waiter.pid);
+ /** Leave a waiting independent landing a slot before a holder takes another lease. */
+ const blockedByLanding = (waiter) => holdsSlot(waiter)
+ && waiters.some((other) => other.landing === 1 && other.pid !== waiter.pid);
+ /** Map queue entries to their declared precedence class. */
+ const rank = (waiter) => waiter.landing === 1 ? 0 : 1;
+ const line = name === 'browser' ? waiters.filter((waiter) => waiter.browser === 1) : waiters;
+ const considered = line.filter((waiter) => !blockedByLanding(waiter)
+ // Browser availability affects admission only; reported positions retain every browser waiter.
+ && (!eligibleOnly || name === 'browser' || waiter.browser !== 1 || !browserBusy));
+ const current = line.find((waiter) => waiter.ticket === ticket);
+ if (!current) return eligibleOnly ? Number.MAX_SAFE_INTEGER : line.length + 1;
+ const currentIndex = considered.findIndex((waiter) => waiter.ticket === ticket);
+ if (currentIndex < 0) return eligibleOnly ? Number.MAX_SAFE_INTEGER : Math.max(2, considered.length + 1);
+ const currentRank = rank(current);
+ return considered.filter((waiter) => rank(waiter) < currentRank || (rank(waiter) === currentRank && waiter.ticket <= ticket)).length;
+}
+
+/** Pause briefly between durable queue checks. */
+function pause(ms) { return new Promise((resolvePromise) => setTimeout(resolvePromise, ms)); }
+
+/**
+ * Join the landing-first queue; every other kind keeps its original FIFO ticket.
+ *
+ * @param {{ name: string, capacity: number, capacityProvider?: () => number, scope?: 'machine'|'repo'|'board', root?: string, agent?: string, repo?: string, landing?: boolean, itemCheck?: boolean, diagnostic?: boolean, browser?: boolean, item?: string, kind?: string, onWait?: (state: object) => void, allowIdleCapacityUpdate?: boolean }} options - Resource identity and queue class.
+ * @returns {Promise<{ name: string, scope: string, token: string, pool: string, browser: boolean, waitMs: number, release: () => void, renew: () => void }>}
+ */
+export async function takeResource(options) {
+ const { name, capacity, scope = 'machine', root = process.cwd(), allowIdleCapacityUpdate = false } = options;
+ if (typeof name !== 'string' || !name.trim() || name.trim() !== name) throw new Refused('BAD_RESOURCE_NAME', 'resource name must be nonempty trimmed text');
+ if (!Number.isSafeInteger(capacity) || capacity < 1) throw new Refused('BAD_RESOURCE_CAPACITY', 'resource capacity must be a positive integer');
+ const landing = options.landing === true;
+ const itemCheck = options.itemCheck === true;
+ const diagnostic = options.diagnostic === true;
+ const browser = options.browser === true;
+ const item = options.item ?? '';
+ const kind = options.kind ?? '';
+ if (browser && name !== 'gate') throw new Refused('BAD_BROWSER_RESOURCE', 'browser capacity can only be acquired together with the machine gate; request name "gate" with browser: true');
+ if (name === 'browser' && !browser) throw new Refused('BAD_BROWSER_RESOURCE', 'browser capacity is acquired only as part of a gate lease; request name "gate" with browser: true');
+ if (typeof item !== 'string' || typeof kind !== 'string') throw new Refused('BAD_RESOURCE_METADATA', 'resource item and kind metadata must be text');
+ if (landing && itemCheck) throw new Refused('BAD_RESOURCE_PRIORITY', 'a gate slot cannot be both a landing and an item check');
+ if (diagnostic && (landing || itemCheck)) throw new Refused('BAD_RESOURCE_PRIORITY', 'a diagnostic slot cannot also be a landing or an item check');
+ const file = databaseFile(scope, root);
+ const db = open(file);
+ let pool;
+ try { pool = canonicalResourceFile(file); }
+ catch (error) { db.close(); throw error; }
+ const token = randomUUID();
+ const requestedAt = Date.now();
+ const pid = process.pid;
+ const agent = options.agent ?? process.env.PULLBOARD_AGENT ?? `pid-${pid}`;
+ const started = processStarted(pid);
+ const repo = options.repo ?? repoRoot(root);
+ let queuedAt = new Date().toISOString();
+ try {
+ update(db, () => {
+ const currentCapacity = options.capacityProvider?.() ?? capacity;
+ if (!Number.isSafeInteger(currentCapacity) || currentCapacity < 1) throw new Refused('BAD_RESOURCE_CAPACITY', 'resource capacity must be a positive integer');
+ const row = db.prepare('SELECT capacity FROM resource WHERE name = ?').get(name);
+ if (row && row.capacity !== currentCapacity) {
+ const state = snapshot(db, name);
+ if (!allowIdleCapacityUpdate || state.holders.length || state.line.length) {
+ throw new Refused('RESOURCE_CAPACITY_MISMATCH', `resource "${name}" already has capacity ${row.capacity}`);
+ }
+ db.prepare('UPDATE resource SET capacity = ? WHERE name = ?').run(currentCapacity, name);
+ }
+ db.prepare('INSERT INTO resource(name, capacity) VALUES (?, ?) ON CONFLICT(name) DO NOTHING').run(name, currentCapacity);
+ if (browser) {
+ const browserResource = db.prepare("SELECT capacity FROM resource WHERE name = 'browser'").get();
+ if (browserResource && browserResource.capacity !== 1) throw new Refused('RESOURCE_CAPACITY_MISMATCH', 'resource "browser" has fixed capacity 1');
+ db.prepare("INSERT INTO resource(name, capacity) VALUES ('browser', 1) ON CONFLICT(name) DO NOTHING").run();
+ }
+ // Retain queue metadata for older readers; admission uses landing priority and arrival only.
+ db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind);
+ });
+ while (true) {
+ const acquired = update(db, () => {
+ const waiter = db.prepare('SELECT ticket FROM waiter WHERE token = ?').get(token);
+ if (!waiter) {
+ queuedAt = new Date().toISOString();
+ const rejoined = db.prepare('INSERT INTO waiter(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, queuedAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind);
+ return { acquired: false, state: { ...snapshot(db, name), position: waiterPosition(db, name, Number(rejoined.lastInsertRowid)), rejoined: true } };
+ }
+ db.prepare('UPDATE waiter SET heartbeat = ? WHERE token = ?').run(Date.now(), token);
+ const spot = snapshot(db, name);
+ const reportPosition = waiterPosition(db, name, waiter.ticket);
+ const admissionPosition = waiterPosition(db, name, waiter.ticket, { eligibleOnly: true });
+ const limit = db.prepare('SELECT capacity FROM resource WHERE name = ?').get(name).capacity;
+ const browserAdmissionPosition = browser ? waiterPosition(db, 'browser', waiter.ticket, { eligibleOnly: true }) : 0;
+ const browserHolders = browser ? db.prepare("SELECT COUNT(*) AS count FROM holder WHERE name = 'gate' AND browser = 1").get().count : 0;
+ if (admissionPosition === 1 && spot.holders.length < limit && (!browser || (browserAdmissionPosition === 1 && browserHolders < 1))) {
+ db.prepare('DELETE FROM waiter WHERE token = ?').run(token);
+ const acquiredAt = new Date().toISOString();
+ db.prepare('INSERT INTO holder(token, name, pid, started, agent, repo, since, heartbeat, landing, item_check, diagnostic, browser, item, kind) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run(token, name, pid, started, agent, repo, acquiredAt, Date.now(), Number(landing), Number(itemCheck || diagnostic), Number(diagnostic), Number(browser), item, kind);
+ return { acquired: true, state: { ...spot, position: 0 } };
+ }
+ return { acquired: false, state: { ...spot, position: reportPosition } };
+ });
+ if (acquired.acquired) {
+ let released = false;
+ let lost = false;
+ const heartbeat = setInterval(() => {
+ if (released || lost) return;
+ try {
+ const changed = update(db, () => db.prepare('UPDATE holder SET heartbeat = ? WHERE token = ?').run(Date.now(), token).changes);
+ if (!changed) { lost = true; clearInterval(heartbeat); }
+ } catch { /* Lease expiry remains the crash fallback. */ }
+ }, HEARTBEAT_MS);
+ heartbeat.unref();
+ /** Release the resource and close its SQLite handle. */
+ const release = () => {
+ if (released) return;
+ released = true;
+ clearInterval(heartbeat);
+ try { update(db, () => db.prepare('DELETE FROM holder WHERE token = ?').run(token)); }
+ finally { db.close(); }
+ };
+ /** Refresh this lease, or refuse if another process already evicted it. */
+ const renew = () => {
+ if (released || lost) throw new Refused('RESOURCE_LEASE_LOST', `resource lease for "${name}" is no longer held`);
+ const changed = update(db, () => db.prepare('UPDATE holder SET heartbeat = ? WHERE token = ?').run(Date.now(), token).changes);
+ if (!changed) {
+ lost = true;
+ clearInterval(heartbeat);
+ throw new Refused('RESOURCE_LEASE_LOST', `resource lease for "${name}" is no longer held`);
+ }
+ };
+ return { name, scope, token, pool, browser, waitMs: Math.max(0, Date.now() - requestedAt), release, renew };
+ }
+ options.onWait?.(acquired.state);
+ await pause(POLL_MS);
+ }
+ } catch (error) {
+ try { update(db, () => db.prepare('DELETE FROM waiter WHERE token = ?').run(token)); } catch { /* Preserve the original error. */ }
+ db.close();
+ throw error;
+ }
+}
+
+/** Reuse a same-machine gate lease in a child without queueing or acquiring a partial browser slot. */
+export function inheritedGateSlot({ root = process.cwd(), browser = false } = {}) {
+ const markedPool = process.env[GATE_SLOT_POOL_ENV] ?? '';
+ const token = process.env[GATE_SLOT_TOKEN_ENV] ?? '';
+ if (!markedPool && !token) return null;
+ if (!markedPool) throw new Refused('GATE_SLOT_MARKER_INVALID', 'the inherited gate token has no pool marker; start the child with gateSlotEnvironment(lease)');
+ const pool = canonicalResourceFile(machineResourceFile());
+ // A process with a different PULLBOARD_MACHINE_HOME is independent and must join its own queue.
+ if (canonicalResourceFile(markedPool) !== pool) return null;
+ if (process.env[GATE_SLOT_HELD_ENV] !== '1') throw new Refused('GATE_SLOT_MARKER_INVALID', 'the inherited gate lease is missing its legacy held marker; start the child with gateSlotEnvironment(lease)');
+ if (!token) throw new Refused('GATE_SLOT_TOKEN_REQUIRED', 'the inherited gate pool marker has no lease token; restart the child with gateSlotEnvironment(lease)');
+ const db = open(pool);
+ let holder;
+ try {
+ holder = update(db, () => db.prepare("SELECT browser FROM holder WHERE name = 'gate' AND token = ?").get(token));
+ } finally { db.close(); }
+ if (!holder) throw new Refused('GATE_SLOT_LEASE_LOST', 'the inherited gate lease is missing or expired; remove stale gate markers or let the parent reacquire the gate slot');
+ const expectedBrowserMarker = holder.browser === 1 ? '1' : '';
+ if (process.env[BROWSER_SLOT_HELD_ENV] !== expectedBrowserMarker) throw new Refused('GATE_SLOT_MARKER_INVALID', 'the inherited browser marker does not match its live gate lease; restart the child with gateSlotEnvironment(lease)');
+ if (browser && holder.browser !== 1) throw new Refused('BROWSER_SLOT_REQUIRED', 'the inherited gate lease does not hold the browser slot; release it and reacquire gate with browser: true before launching Chrome');
+ return {
+ name: 'gate', scope: 'machine', token, pool, browser: holder.browser === 1, waitMs: 0,
+ release() {}, renew() {},
+ };
+}
+
+/** Change a resource's capacity only while its queue is empty, persisting related settings under the same lock. */
+export function setResourceCapacity({ name, capacity, scope = 'machine', root = process.cwd(), persist = () => {} }) {
+ if (typeof name !== 'string' || !name.trim() || name.trim() !== name) throw new Refused('BAD_RESOURCE_NAME', 'resource name must be nonempty trimmed text');
+ if (!Number.isSafeInteger(capacity) || capacity < 1) throw new Refused('BAD_RESOURCE_CAPACITY', 'resource capacity must be a positive integer');
+ if (name === 'browser' && capacity !== 1) throw new Refused('BAD_RESOURCE_CAPACITY', 'browser resource capacity is fixed at 1');
+ const db = open(databaseFile(scope, root));
+ try {
+ return update(db, () => {
+ const state = snapshot(db, name);
+ if (state.holders.length || state.line.length) {
+ throw new Refused('RESOURCE_BUSY', `resource "${name}" has ${state.holders.length} holder(s) and ${state.line.length} waiter(s); wait for it to become idle, then retry pullboard settings gateSlots ${capacity}`);
+ }
+ persist();
+ db.prepare('INSERT INTO resource(name, capacity) VALUES (?, ?) ON CONFLICT(name) DO UPDATE SET capacity = excluded.capacity').run(name, capacity);
+ return { name, capacity };
+ });
+ } finally { db.close(); }
+}
+
+/** List resources and prune leases whose process died or lease expired. */
+export function listResources({ scope = 'machine', root = process.cwd() } = {}) {
+ const db = open(databaseFile(scope, root));
+ try {
+ return update(db, () => db.prepare('SELECT name, capacity FROM resource ORDER BY name').all().map(({ name, capacity }) => ({ name, capacity, ...snapshot(db, name) })));
+ } finally { db.close(); }
+}
diff --git a/test/runners.test.js b/test/runners.test.js
index 66bef305..fac43723 100644
--- a/test/runners.test.js
+++ b/test/runners.test.js
@@ -8,6 +8,7 @@ import { DatabaseSync } from 'node:sqlite';
import { tmpdir } from 'node:os';
import { test } from 'node:test';
import { takeResource } from '../src/resources.js';
+import { listResources as listPreRunnerResources, takeResource as takePreRunnerResource } from './fixtures/resources-pre-runners.js';
import { runFixtureChild, startFixtureChild } from './fixture-child.js';
const BIN = resolve(import.meta.dirname, '../bin/pullboard.js');
@@ -99,7 +100,9 @@ ${dropFirst ? `if (host.endsWith('-drop') && call === 1) {
PULLBOARD_HOME: home, PULLBOARD_MACHINE_HOME: machineHome, LANG: 'C', LC_ALL: 'C', TZ: 'UTC' };
// Replace the marker-driven shell so the injected HUP reaches the actual worker process.
const child = spawn('/bin/sh', ['-c', dropAfterMarker ? 'exec ' + remoteCommand : remoteCommand], { cwd: worker, env,
- stdio: ['pipe', 'inherit', 'inherit'] });
+ stdio: ['pipe', 'pipe', 'pipe'] });
+ child.stdout.pipe(process.stdout);
+ child.stderr.pipe(process.stderr);
process.stdin.pipe(child.stdin);
let droppedAfterSetup = false;
if (dropAfterMarker) {
@@ -143,7 +146,7 @@ test('runner executed the committed source in its private checkout', () => {
const tree = execFileSync('git', ['rev-parse', 'HEAD^{tree}'], { encoding: 'utf8' }).trim();
const shallow = execFileSync('git', ['rev-parse', '--is-shallow-repository'], { encoding: 'utf8' }).trim();
const count = execFileSync('git', ['rev-list', '--count', 'HEAD'], { encoding: 'utf8' }).trim();
- const history = execFileSync('git', ['log', '--follow', '--format=%H', '--', 'history-renamed.txt'], { encoding: 'utf8' }).trim().split(/\r?\n/u);
+ const history = execFileSync('git', ['log', '--follow', '--format=%H', '--', 'history-renamed.txt'], { encoding: 'utf8' }).trim().split(/\\r?\\n/u);
const runnerHome = process.env.HOME;
const privateHomeRelative = relative(${JSON.stringify(remoteStateRoot)}, runnerHome);
assert.ok(privateHomeRelative && !privateHomeRelative.startsWith('..' + sep) && privateHomeRelative !== '..', runnerHome);
@@ -199,9 +202,11 @@ test('a cached workspace link resolves inside this fresh runner checkout', () =>
assert.equal(process.execPath, ${JSON.stringify(nodePath)}, 'the configured runner Node executes the command');
const commit = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
const tree = execFileSync('git', ['rev-parse', 'HEAD^{tree}'], { encoding: 'utf8' }).trim();
+ const generated = JSON.parse(readFileSync(join(root, 'generated/config.json'), 'utf8'));
+ assert.equal(generated.root, root, 'root prepare ran in this fresh checkout and generated a job-local file');
const shallow = execFileSync('git', ['rev-parse', '--is-shallow-repository'], { encoding: 'utf8' }).trim();
const count = execFileSync('git', ['rev-list', '--count', 'HEAD'], { encoding: 'utf8' }).trim();
- const history = execFileSync('git', ['log', '--follow', '--format=%H', '--', 'history-renamed.txt'], { encoding: 'utf8' }).trim().split(/\r?\n/u);
+ const history = execFileSync('git', ['log', '--follow', '--format=%H', '--', 'history-renamed.txt'], { encoding: 'utf8' }).trim().split(/\\r?\\n/u);
assert.equal(shallow, 'false', 'the cache contains full candidate history');
assert.equal(count, '3', 'the cache preserves the complete selected history');
assert.ok(history.includes(${JSON.stringify(historyBaseCommit)}), 'cached history follows the original filename through the rename');
@@ -213,7 +218,7 @@ test('a cached workspace link resolves inside this fresh runner checkout', () =>
assert.equal(target, join(root, 'packages/runner-fixture-dep'));
const targetRelative = relative(root, target);
assert.ok(targetRelative && !targetRelative.startsWith('..' + sep) && targetRelative !== '..');
- console.log('RUNNER_CACHE_FACT ' + JSON.stringify({ root, link, target, commit, tree, shallow, count, history }));
+ console.log('RUNNER_CACHE_FACT ' + JSON.stringify({ root, link, target, commit, tree, shallow, count, history, generatedRoot: generated.root }));
});
`;
writeFileSync(join(repo, 'runner-cache-probe.test.js'), probe);
@@ -241,6 +246,11 @@ function gateResult(stdout) {
return JSON.parse(line.slice('PULLBOARD_RUN_RESULT '.length));
}
+/** Include bounded command output when a remote fixture assertion fails. */
+function fixtureResultContext(result) {
+ return `${result.context}\nstdout tail:\n${String(result.stdout ?? '').slice(-4_000)}\nstderr tail:\n${String(result.stderr ?? '').slice(-4_000)}`;
+}
+
/** Read the remote machine's live gate holders without changing its shared admission state. */
function readRemoteGateHolders(file) {
const db = new DatabaseSync(file, { readOnly: true });
@@ -270,6 +280,25 @@ async function waitForMarker(path) {
} finally { clearTimeout(timer); watcher.close(); }
}
+/** Poll a concrete process/resource state; the deadline only bounds a broken cleanup handshake. */
+async function waitForCondition(check, label) {
+ const deadline = Date.now() + 20_000;
+ while (!check()) {
+ if (Date.now() >= deadline) throw new Error(`fixture cleanup state did not arrive: ${label}`);
+ await new Promise(resolve => setTimeout(resolve, 20)); // budget: polling interval for an observable cleanup condition.
+ }
+}
+
+/** Check exact PID presence without signalling or treating permission denial as absence. */
+function processIsAlive(pid) {
+ try { process.kill(pid, 0); return true; }
+ catch (error) {
+ if (error.code === 'ESRCH') return false;
+ if (error.code === 'EPERM') return true;
+ throw error;
+ }
+}
+
/** Wait for the stand-in to record a particular invocation count, not for elapsed time. */
async function waitForRequestCount(path, count) {
if (existsSync(path) && readFileSync(path, 'utf8').trim().split('\n').length >= count) return;
@@ -408,7 +437,7 @@ test('a queued run executes on a registered runner and its result comes back [C7
held = await takeResource({ name: 'gate', capacity: 1, scope: 'machine', root: repo,
agent: 'fixture-local-holder', item: 'runner-local-holder', kind: 'force-registered-runner' });
const successful = runThroughGate(repo, env, 'node --test --test-reporter=tap runner-probe.test.js');
- assert.equal(successful.status, 0, successful.context);
+ assert.equal(successful.status, 0, fixtureResultContext(successful));
assert.match(successful.stdout, /TAP version 13/);
assert.match(successful.stdout, /RUNNER_FACT /);
const fact = JSON.parse(/RUNNER_FACT (\{[^\n]+\})/u.exec(successful.stdout)?.[1] ?? 'null');
@@ -454,7 +483,7 @@ test('a queued run executes on a registered runner and its result comes back [C7
assert.doesNotMatch(successful.stdout + successful.stderr, new RegExp(SECRET, 'u'));
const red = runThroughGate(repo, env, "node -e 'process.stdout.write(\"RUNNER_EXIT_7\\n\"); process.exit(7)'");
- assert.equal(red.status, 1, red.context);
+ assert.equal(red.status, 1, fixtureResultContext(red));
assert.match(red.stdout, /RUNNER_EXIT_7/);
const redResult = gateResult(red.stdout);
assert.equal(redResult.isGreen, false);
@@ -471,9 +500,11 @@ test('a queued run executes on a registered runner and its result comes back [C7
assert.doesNotMatch(git(repo, env, 'ls-tree', '-r', '--name-only', 'HEAD'), /(?:^|\n)\.env(?:$|\n)/u);
assert.equal(readFileSync(join(repo, '.env'), 'utf8'), SECRET, 'the ignored local fixture remains private');
const historicalRed = runThroughGate(repo, env, 'node -e "process.stdout.write(\'HISTORICAL_SECRET_SCAN_REACHED\\n\')"');
- assert.equal(historicalRed.status, 1, historicalRed.context);
+ assert.equal(historicalRed.status, 1, fixtureResultContext(historicalRed));
assert.match(historicalRed.stdout + historicalRed.stderr, /RUNNER_SECRET/u);
assert.doesNotMatch(historicalRed.stdout + historicalRed.stderr, new RegExp(SECRET, 'u'));
+ assert.equal(readFileSync(requests, 'utf8').trim().split('\n').length, callsAfterExit7,
+ 'historical secret scanning refuses before opening an SSH request');
assert.equal(commit.length, 40);
assert.equal(tree.length, 40);
@@ -711,7 +742,7 @@ writeFileSync(ready, 'setup started\\n');
}
});
-test('a queued run executes on a registered runner and its result comes back [C7] (cached workspace dependencies stay linked to fresh checkouts)', async (t) => {
+test('a queued run executes on a registered runner and its result comes back [C7] (cached source and npm content retain fresh checkout lifecycles)', async (t) => {
const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-runner-cache-')));
t.after(() => rmSync(dir, { recursive: true, force: true }));
const home = join(dir, 'home');
@@ -737,12 +768,18 @@ test('a queued run executes on a registered runner and its result comes back [C7
};
const initialized = runFixtureChild('git', ['init', '-q', '-b', 'main'], { cwd: repo, env, encoding: 'utf8' });
assert.equal(initialized.status, 0, initialized.context);
- writeFileSync(join(repo, '.gitignore'), 'node_modules/\n');
+ writeFileSync(join(repo, '.gitignore'), 'node_modules/\ngenerated/\n');
writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({ gate: 'true' }));
writeFileSync(join(repo, 'package.json'), JSON.stringify({
name: 'runner-cache-fixture', version: '1.0.0', private: true, type: 'module',
+ scripts: { prepare: 'node prepare.js' },
workspaces: ['packages/runner-fixture-dep'], dependencies: { 'runner-fixture-dep': '1.0.0' },
}, null, 2) + '\n');
+ writeFileSync(join(repo, 'prepare.js'), `import { mkdirSync, writeFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+mkdirSync('generated', { recursive: true });
+writeFileSync('generated/config.json', JSON.stringify({ root: resolve('.') }) + '\\n');
+`);
writeFileSync(join(packageDirectory, 'package.json'), JSON.stringify({
name: 'runner-fixture-dep', version: '1.0.0', type: 'module', scripts: { postinstall: 'node postinstall.js' },
}, null, 2) + '\n');
@@ -762,7 +799,7 @@ appendFileSync(${JSON.stringify(installWitnesses)}, 'postinstall\\n');
cwd: repo, env, encoding: 'utf8',
});
assert.equal(lock.status, 0, lock.context);
- git(repo, env, 'add', '.gitignore', 'pullboard.json', 'package.json', 'package-lock.json', 'packages/runner-fixture-dep', 'history-original.txt');
+ git(repo, env, 'add', '.gitignore', 'pullboard.json', 'package.json', 'prepare.js', 'package-lock.json', 'packages/runner-fixture-dep', 'history-original.txt');
git(repo, env, 'commit', '-q', '-m', 'test: prepare cached local workspace dependency');
const historyBaseCommit = git(repo, env, 'rev-parse', 'HEAD');
git(repo, env, 'mv', 'history-original.txt', 'history-renamed.txt');
@@ -790,7 +827,7 @@ appendFileSync(${JSON.stringify(installWitnesses)}, 'postinstall\\n');
const cacheCommit = git(repo, env, 'rev-parse', 'HEAD');
const cacheTree = git(repo, env, 'rev-parse', 'HEAD^{tree}');
const first = runThroughGate(repo, env, command, { item: 'cache-first' });
- assert.equal(first.status, 0, first.context);
+ assert.equal(first.status, 0, fixtureResultContext(first));
const firstFact = JSON.parse(/RUNNER_CACHE_FACT (\{[^\n]+\})/u.exec(first.stdout)?.[1] ?? 'null');
assert.equal(firstFact.commit, cacheCommit);
assert.equal(firstFact.tree, cacheTree);
@@ -798,25 +835,27 @@ appendFileSync(${JSON.stringify(installWitnesses)}, 'postinstall\\n');
assert.ok(firstFact.history.includes(historyBaseCommit));
assert.equal(firstFact.root, firstFact.target.slice(0, firstFact.target.indexOf('/packages/runner-fixture-dep')));
assert.equal(gateResult(first.stdout).runner, HOST);
- assert.equal(readFileSync(installWitnesses, 'utf8'), 'postinstall\n', 'the first exact-tree run installs the committed workspace dependency');
+ assert.equal(firstFact.generatedRoot, firstFact.root, 'the first fresh checkout ran root prepare');
+ assert.equal(readFileSync(installWitnesses, 'utf8'), 'postinstall\n', 'the first fresh checkout runs the committed workspace postinstall');
const second = runThroughGate(repo, env, command, { item: 'cache-second' });
- assert.equal(second.status, 0, second.context);
+ assert.equal(second.status, 0, fixtureResultContext(second));
const secondFact = JSON.parse(/RUNNER_CACHE_FACT (\{[^\n]+\})/u.exec(second.stdout)?.[1] ?? 'null');
assert.equal(secondFact.commit, cacheCommit);
assert.equal(secondFact.tree, cacheTree);
assert.equal(secondFact.shallow, 'false');
assert.ok(secondFact.history.includes(historyBaseCommit));
+ assert.equal(secondFact.generatedRoot, secondFact.root, 'the second fresh checkout reran root prepare');
assert.equal(gateResult(second.stdout).runner, HOST);
assert.equal(secondFact.root, secondFact.target.slice(0, secondFact.target.indexOf('/packages/runner-fixture-dep')));
assert.notEqual(firstFact.root, secondFact.root, 'each run unpacks a fresh checkout');
assert.equal(git(repo, env, 'rev-parse', 'HEAD'), cacheCommit);
assert.equal(git(repo, env, 'rev-parse', 'HEAD^{tree}'), cacheTree);
- assert.equal(readFileSync(installWitnesses, 'utf8'), 'postinstall\n', 'the second run reuses the dependency cache without a second install witness');
+ assert.equal(readFileSync(installWitnesses, 'utf8'), 'postinstall\npostinstall\n', 'the second fresh checkout runs its own workspace postinstall');
const requestsSeen = readFileSync(requests, 'utf8').trim().split('\n').map(line => JSON.parse(line));
assert.equal(requestsSeen.length, 2);
assert.ok(requestsSeen[0].stdinBytes > requestsSeen[1].stdinBytes,
- 'the cache hit sends fewer Git-pack bytes for the same selected candidate');
+ 'the same candidate sends fewer Git-pack bytes after its first cache import');
assert.ok(requestsSeen.every(request => request.remoteStartsWithConfiguredNode), 'both remote workers use the configured absolute Node path');
} finally {
if (held) held.release();
@@ -826,3 +865,260 @@ appendFileSync(${JSON.stringify(installWitnesses)}, 'postinstall\\n');
else process.env.PULLBOARD_MACHINE_HOME = previousMachineHome;
}
});
+
+test('a queued run executes on a registered runner and its result comes back [C7] (older resource clients keep local capacity separate)', async (t) => {
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-runner-old-resource-client-')));
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+ const home = join(dir, 'home');
+ const machineHome = join(home, '.pullboard');
+ const remoteHome = join(dir, 'worker-home');
+ const remoteMachineHome = join(remoteHome, '.pullboard');
+ const repo = join(dir, 'repo');
+ const worker = join(dir, 'second-machine');
+ const bin = join(dir, 'bin');
+ const requests = join(dir, 'ssh-requests.jsonl');
+ const remoteReady = join(dir, 'remote-ready');
+ const releaseRemote = join(dir, 'release-remote');
+ const secondBrowserQueued = join(dir, 'second-browser-queued');
+ const secondBrowserAcquired = join(dir, 'second-browser-acquired');
+ const resourceDatabase = join(machineHome, 'resources.sqlite');
+ for (const folder of [repo, worker, bin, home, machineHome, remoteHome, remoteMachineHome]) {
+ mkdirSync(folder, { recursive: true });
+ }
+ writeFileSync(join(machineHome, 'settings.json'), JSON.stringify({ gateSlots: 2 }));
+ const env = {
+ ...process.env, HOME: home, PULLBOARD_HOME: home, PULLBOARD_MACHINE_HOME: machineHome,
+ PATH: `${bin}:${process.env.PATH}`, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',
+ GIT_AUTHOR_NAME: 'Legacy Resource Fixture', GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Legacy Resource Fixture', GIT_COMMITTER_EMAIL: '[email protected]',
+ };
+ const initialized = runFixtureChild('git', ['init', '-q', '-b', 'main'], { cwd: repo, env, encoding: 'utf8' });
+ assert.equal(initialized.status, 0, initialized.context);
+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({ gate: 'true' }));
+ writeFileSync(join(repo, 'tracked.txt'), 'registered runner fixture\n');
+ git(repo, env, 'add', 'pullboard.json', 'tracked.txt');
+ git(repo, env, 'commit', '-q', '-m', 'test: prepare mixed-version resource fixture');
+ installSshStandIn({ bin, worker, home: remoteHome, machineHome: remoteMachineHome, requests });
+ const added = cli(repo, env, 'runner', 'add', HOST, '--slots', '1', '--browser', '1', '--json');
+ assert.equal(added.status, 0, added.context);
+
+ const previousHome = process.env.PULLBOARD_HOME;
+ const previousMachineHome = process.env.PULLBOARD_MACHINE_HOME;
+ process.env.PULLBOARD_HOME = home;
+ process.env.PULLBOARD_MACHINE_HOME = machineHome;
+ let initialBrowser;
+ let localBrowser;
+ let localCpu;
+ let secondBrowser;
+ let secondBrowserPromise;
+ let remoteRun;
+ const inspectCapacity = expectedLocal => {
+ const db = new DatabaseSync(resourceDatabase, { readOnly: true });
+ try {
+ const local = db.prepare("SELECT name, runner, browser FROM holder WHERE name = 'gate'").all();
+ const remote = db.prepare('SELECT name, runner, browser FROM holder WHERE runner = ?').all(HOST);
+ assert.equal(db.prepare("SELECT capacity FROM resource WHERE name = 'gate'").get()?.capacity, 2);
+ assert.equal(db.prepare("SELECT capacity FROM resource WHERE name = 'browser'").get()?.capacity, 1);
+ const browserCount = local.filter(holder => holder.browser === 1).length;
+ assert.ok(local.length <= 2, 'local gate holders stay within the real SQLite gate capacity');
+ assert.ok(browserCount <= 1, 'local browser holders stay within the real SQLite browser capacity');
+ assert.equal(local.length, expectedLocal);
+ assert.equal(remote.length, 1, 'the remote runner holder remains independent of local capacity');
+ assert.equal(remote[0].name, `runner:${HOST}`);
+ return { local, remote, browserCount };
+ } finally { db.close(); }
+ };
+ try {
+ initialBrowser = await takePreRunnerResource({ name: 'gate', capacity: 2, scope: 'machine', root: repo,
+ agent: 'pre-runner-initial-browser', item: 'pre-runner-initial-browser', kind: 'fixture-hold', browser: true });
+ const remoteCode = `const fs=require('node:fs'); const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
+(async()=>{ fs.writeFileSync(${JSON.stringify(remoteReady)}, 'ready\\n'); while(!fs.existsSync(${JSON.stringify(releaseRemote)})) await sleep(5); })().catch(error=>{console.error(error);process.exitCode=2});`;
+ remoteRun = observe(startQueueController(repo, env, `node -e ${shellQuote(remoteCode)}`,
+ { item: 'remote-capacity-holder', queueMarker: null, firstItem: null }));
+ await waitForMarker(remoteReady);
+
+ const heldBesideRemote = inspectCapacity(1);
+ assert.equal(heldBesideRemote.browserCount, 1, 'the remote lease leaves the legacy local browser holder unchanged');
+
+ initialBrowser.release();
+ initialBrowser = null;
+ localBrowser = await takePreRunnerResource({ name: 'gate', capacity: 2, scope: 'machine', root: repo,
+ agent: 'pre-runner-browser-one', item: 'pre-runner-browser-one', kind: 'fixture-browser', browser: true });
+ localCpu = await takePreRunnerResource({ name: 'gate', capacity: 2, scope: 'machine', root: repo,
+ agent: 'pre-runner-cpu', item: 'pre-runner-cpu', kind: 'fixture-cpu' });
+ secondBrowserPromise = takePreRunnerResource({ name: 'gate', capacity: 2, scope: 'machine', root: repo,
+ agent: 'pre-runner-browser-two', item: 'pre-runner-browser-two', kind: 'fixture-browser', browser: true,
+ onWait(state) {
+ if (state.line?.some(waiter => waiter.item === 'pre-runner-browser-two')) {
+ writeFileSync(secondBrowserQueued, 'queued\n');
+ }
+ },
+ }).then(lease => {
+ secondBrowser = lease;
+ writeFileSync(secondBrowserAcquired, 'acquired\n');
+ return lease;
+ });
+ await waitForMarker(secondBrowserQueued);
+ assert.equal(existsSync(secondBrowserAcquired), false, 'a second local browser waits even while its first slot is held');
+
+ const duringRemote = listPreRunnerResources({ scope: 'machine', root: repo });
+ const localGate = duringRemote.find(resource => resource.name === 'gate');
+ const runnerResource = duringRemote.find(resource => resource.name === `runner:${HOST}`);
+ assert.equal(localGate.holders.length, 2, 'the old API admits one local browser and one local CPU lease');
+ assert.equal(localGate.holders.filter(holder => holder.browser).length, 1);
+ assert.equal(runnerResource.holders.length, 1, 'the registered runner remains held independently');
+ assert.equal(inspectCapacity(2).browserCount, 1);
+ assert.equal(existsSync(secondBrowserAcquired), false, 'local browser capacity remains one');
+
+ localCpu.release();
+ localCpu = null;
+ localBrowser.release();
+ localBrowser = null;
+ await waitForMarker(secondBrowserAcquired);
+ secondBrowser = await secondBrowserPromise;
+ const afterHandoff = listPreRunnerResources({ scope: 'machine', root: repo });
+ assert.equal(afterHandoff.find(resource => resource.name === 'gate').holders.length, 1);
+ assert.equal(afterHandoff.find(resource => resource.name === `runner:${HOST}`).holders.length, 1,
+ 'the remote run is still live while the old API hands off the local browser slot');
+ assert.equal(inspectCapacity(1).browserCount, 1);
+ secondBrowser.release();
+ secondBrowser = null;
+ writeFileSync(releaseRemote, 'release\n');
+ const completed = await remoteRun.closed;
+ remoteRun = null;
+ assert.equal(completed.status, 0, fixtureResultContext(completed));
+ assert.equal(gateResult(completed.stdout).runner, HOST);
+ } finally {
+ for (const lease of [initialBrowser, localBrowser, localCpu, secondBrowser]) lease?.release();
+ writeFileSync(releaseRemote, 'cleanup-release\n');
+ if (secondBrowserPromise && !secondBrowser) {
+ try { secondBrowser = await secondBrowserPromise; secondBrowser.release(); secondBrowser = null; } catch {}
+ }
+ if (remoteRun) {
+ await remoteRun.closed;
+ }
+ if (previousHome === undefined) delete process.env.PULLBOARD_HOME;
+ else process.env.PULLBOARD_HOME = previousHome;
+ if (previousMachineHome === undefined) delete process.env.PULLBOARD_MACHINE_HOME;
+ else process.env.PULLBOARD_MACHINE_HOME = previousMachineHome;
+ }
+});
+
+test('a queued run executes on a registered runner and its result comes back [C7] (parent death drains a detached worker descendant before releasing its lease)', async (t) => {
+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'pullboard-runner-parent-death-')));
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
+ const home = join(dir, 'home');
+ const machineHome = join(home, '.pullboard');
+ const remoteHome = join(dir, 'worker-home');
+ const remoteMachineHome = join(remoteHome, '.pullboard');
+ const remoteDatabase = join(remoteMachineHome, 'resources.sqlite');
+ const repo = join(dir, 'repo');
+ const worker = join(dir, 'second-machine');
+ const bin = join(dir, 'bin');
+ const requests = join(dir, 'ssh-requests.jsonl');
+ const childReady = join(dir, 'detached-child-ready');
+ const childPidFile = join(dir, 'detached-child-pid');
+ const childTerm = join(dir, 'detached-child-term');
+ const releaseChild = join(dir, 'release-detached-child');
+ const childGone = join(dir, 'detached-child-gone');
+ for (const folder of [repo, worker, bin, home, machineHome, remoteHome, remoteMachineHome]) {
+ mkdirSync(folder, { recursive: true });
+ }
+ writeFileSync(join(machineHome, 'settings.json'), JSON.stringify({ gateSlots: 1 }));
+ const env = {
+ ...process.env, HOME: home, PULLBOARD_HOME: home, PULLBOARD_MACHINE_HOME: machineHome,
+ PATH: `${bin}:${process.env.PATH}`, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1',
+ GIT_AUTHOR_NAME: 'Parent Death Fixture', GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Parent Death Fixture', GIT_COMMITTER_EMAIL: '[email protected]',
+ };
+ const initialized = runFixtureChild('git', ['init', '-q', '-b', 'main'], { cwd: repo, env, encoding: 'utf8' });
+ assert.equal(initialized.status, 0, initialized.context);
+ writeFileSync(join(repo, 'pullboard.json'), JSON.stringify({ gate: 'true' }));
+ writeFileSync(join(repo, 'tracked.txt'), 'parent-death runner fixture\n');
+ writeFileSync(join(repo, 'remote-parent-death-launcher.js'), `const { spawn } = require('node:child_process');
+const child = spawn(process.execPath, [require.resolve('./remote-detached-child.js'), ...process.argv.slice(2)], {
+ detached: true, stdio: 'ignore', env: process.env,
+});
+child.unref();
+setInterval(() => {}, 1_000);
+`);
+ writeFileSync(join(repo, 'remote-detached-child.js'), `const { existsSync, writeFileSync } = require('node:fs');
+const [ready, pidFile, term, release, gone] = process.argv.slice(2);
+let handlingTerm = false;
+process.on('SIGTERM', () => {
+ if (handlingTerm) return;
+ handlingTerm = true;
+ writeFileSync(term, 'term\\n');
+ const wait = setInterval(() => {
+ if (!existsSync(release)) return;
+ clearInterval(wait);
+ writeFileSync(gone, 'gone\\n');
+ process.exit(0);
+ }, 5);
+});
+writeFileSync(pidFile, String(process.pid));
+writeFileSync(ready, 'ready\\n');
+setInterval(() => {}, 1_000);
+`);
+ git(repo, env, 'add', 'pullboard.json', 'tracked.txt', 'remote-parent-death-launcher.js', 'remote-detached-child.js');
+ git(repo, env, 'commit', '-q', '-m', 'test: prepare committed detached-child launchers');
+ installSshStandIn({ bin, worker, home: remoteHome, machineHome: remoteMachineHome, requests });
+ const added = cli(repo, env, 'runner', 'add', HOST, '--slots', '1', '--browser', '1', '--json');
+ assert.equal(added.status, 0, added.context);
+
+ const previousHome = process.env.PULLBOARD_HOME;
+ const previousMachineHome = process.env.PULLBOARD_MACHINE_HOME;
+ process.env.PULLBOARD_HOME = home;
+ process.env.PULLBOARD_MACHINE_HOME = machineHome;
+ let localHold;
+ let remoteRun;
+ let detachedPid;
+ let remoteAgent;
+ try {
+ localHold = await takeResource({ name: 'gate', capacity: 1, scope: 'machine', root: repo,
+ agent: 'parent-death-local-holder', item: 'parent-death-local-holder', kind: 'fixture-hold', browser: true });
+ const command = ['node remote-parent-death-launcher.js', ...[childReady, childPidFile, childTerm, releaseChild, childGone].map(shellQuote)].join(' ');
+ remoteRun = observe(startQueueController(repo, env, command,
+ { item: 'parent-death-remote-holder', queueMarker: null, firstItem: null }));
+ await waitForMarker(childReady);
+ detachedPid = Number(readFileSync(childPidFile, 'utf8').trim());
+ assert.ok(Number.isSafeInteger(detachedPid) && detachedPid > 0);
+ assert.notEqual(detachedPid, remoteRun.child.pid, 'the committed launcher owns a separate detached child');
+ assert.equal(processIsAlive(detachedPid), true);
+ const held = readRemoteGateHolders(remoteDatabase);
+ assert.equal(held.length, 1, 'the remote worker keeps its physical gate holder while the launcher is live');
+ remoteAgent = held[0].agent;
+ assert.match(remoteAgent, /^pullboard-ssh-/u);
+
+ remoteRun.child.kill('SIGTERM');
+ await waitForMarker(childTerm);
+ assert.equal(processIsAlive(detachedPid), true, 'the detached child remains alive in its controlled TERM handler');
+ const duringDrain = readRemoteGateHolders(remoteDatabase);
+ assert.equal(duringDrain.length, 1);
+ assert.equal(duringDrain[0].agent, remoteAgent, 'the physical runner lease remains held during descendant cleanup');
+
+ writeFileSync(releaseChild, 'release\n');
+ await waitForMarker(childGone);
+ await waitForCondition(() => !processIsAlive(detachedPid), 'the detached child PID exits');
+ await waitForCondition(() => readRemoteGateHolders(remoteDatabase).every(holder => holder.agent !== remoteAgent),
+ 'the remote physical gate holder is released after child exit');
+ const controller = await remoteRun.closed;
+ remoteRun = null;
+ assert.equal(controller.signal, 'SIGTERM', 'the owned API controller alone received SIGTERM');
+ } finally {
+ if (localHold) localHold.release();
+ writeFileSync(releaseChild, 'cleanup-release\n');
+ if (remoteRun && remoteRun.child.exitCode === null && remoteRun.child.signalCode === null) {
+ remoteRun.child.kill('SIGTERM');
+ }
+ if (detachedPid && processIsAlive(detachedPid)) {
+ try { process.kill(detachedPid, 'SIGTERM'); } catch (error) { if (error.code !== 'ESRCH') throw error; }
+ }
+ if (remoteRun) await remoteRun.closed;
+ if (detachedPid) await waitForCondition(() => !processIsAlive(detachedPid), 'fixture detached child cleanup');
+ if (previousHome === undefined) delete process.env.PULLBOARD_HOME;
+ else process.env.PULLBOARD_HOME = previousHome;
+ if (previousMachineHome === undefined) delete process.env.PULLBOARD_MACHINE_HOME;
+ else process.env.PULLBOARD_MACHINE_HOME = previousMachineHome;
+ }
+});