diff --git a/docs/decisions/ci-utility.md b/docs/decisions/ci-utility.md index 1d21b87ddb..98ca30d867 100644 --- a/docs/decisions/ci-utility.md +++ b/docs/decisions/ci-utility.md @@ -169,7 +169,7 @@ Local import-graph feedback uses eight workers on the measured 32-CPU, 47-GiB host. The default is `max(1, min(floor(cores / 4), floor(RAM * 0.7 / 2 GiB)))`, with `--import-graph-workers=N` as the override (`localUnitWorkerCount`, -`scripts/unit-workers.ts:15-17`). Changed-mode workers use one fresh prepared +`scripts/unit-workers.ts:16-18`). Changed-mode workers use one fresh prepared build and private overlay views; `unit-workers --private-tree` retains the ordinary private-build comparison. Hosted explicit-file partitions retain `balanceTests`, their private builds and N=2. diff --git a/docs/process/ci-throughput.md b/docs/process/ci-throughput.md index 0f26045a60..c5ba7c9957 100644 --- a/docs/process/ci-throughput.md +++ b/docs/process/ci-throughput.md @@ -94,6 +94,8 @@ ID/time permit attributed historical observations. IDs cannot be overwritten with different content. Pairs are `work-started`/`work-finished` and `wait-started`/`wait-finished`; waits require `reason` set to `reservation`, `ci`, `review`, `conflict` or `other`. Each pair shares worker/task/reason. +Host admission records each wait for a heavy local slot as a pair with reason +`other` and task `admission-` ([host admission](testing.md#host-admission-for-heavy-local-commands)). Unmatched records remain unknown; overlapping tasks on one worker do not create two workers. Complete task intervals measure task lifetime, not CPU busy time or token cost. No records means unknown worker concurrency. This endpoint does diff --git a/docs/process/testing.md b/docs/process/testing.md index bbe92e4bbc..87c163067d 100644 --- a/docs/process/testing.md +++ b/docs/process/testing.md @@ -412,6 +412,53 @@ permits setup failures and does not belong in proof. A PATH change on the host does not upgrade a fixed `/usr/bin/bwrap` inside a container; qualify that runtime separately before changing its supplied binary. Hosted CI images stay unchanged. +## Host admission for heavy local commands + +Local long suites are for debugging a specific failure only (#2939); they run +through a host-wide admission ledger, `scripts/host-admission.mjs` (#2943). +Separate worktrees on one machine share its slots, so a heavy command that +would exceed the limit waits, printing the holders and its queue position, +instead of starting and timing out. Test deadlines are never raised to absorb +contention. + +Heavy commands are the integrated default `bun run test` suite, runtime-host +and native test selections, any selected file whose measured cost in +`scripts/test-shard-costs.json` reaches 30 seconds, `check:pr --full`/`--all`, +the parallel unit-worker queue (one slot for all its workers) and +`bun run test:browser` (held on the host for the whole container run). Focused +tests and default `check:pr` are not admitted. Nested heavy commands inherit +their caller's slot, also when a caller replaced their environment: the +ledger itself shows a live ancestor holding a slot. The admitted command +receives the workspace lease's descriptor, as a nested user namespace needs. A wait is recorded as a `wait-started`/`wait-finished` +pair with reason `other` through `scripts/ci-timings.ts record` +([coordination events](ci-throughput.md#record-coordination-and-incidents)). + +| Variable | Meaning | +| --- | --- | +| `BRAIN_HOST_ADMISSION_LIMIT` | Concurrent heavy commands admitted on this host. Defaults to one per four CPUs, at least 1; anything but a positive integer is refused. | +| `BRAIN_HOST_ADMISSION_DIR` | Ledger directory. Defaults to `brain-host-admission-` under the system temporary directory. The test preload gives each test process a private ledger, which its descendants also find through their ancestry; a test exercising the host ledger names its own. | +| `BRAIN_WORKER_ID`, `BRAIN_ORCHESTRATOR_ID` | Opaque worker and orchestrator IDs recorded with each slot. Without them a worker is `host-` and has no orchestrator; it still gets the admission limit. | +| `BRAIN_RED_MAIN_FIX` | The PR number of a declared red-main fix. Its commands are admitted ahead of every queued ordinary command; they do not preempt running ones. Equivalent to `run --red-main-fix `. | +| `BRAIN_HOST_ADMISSION` | Internal: the slot an admitted command's descendants inherit. Never set it by hand. | + +```sh +node scripts/host-admission.mjs status +node scripts/host-admission.mjs run [--red-main-fix ] -- +node scripts/host-admission.mjs preempt --reason red-main-fix [--grace-ms 10000] +``` + +The ledger records each slot's holder process identity, worker, orchestrator +and priority class. A holder whose process has died is reclaimed on the next +pass, after its orphaned command group has been killed. `preempt` follows the +[#2938 ruling](https://github.com/schlessera/brain-kit/issues/2938): it refuses +a slot outside the caller's orchestrator subtree, any reason but +`red-main-fix`, and a call while no red-main fix is waiting. It sends SIGTERM to +the holder's process group, lets cleanup run for the grace period, then kills +it; the slot is released only after the group has gone. The preempted run exits +`75` and is recorded as `preempted` in the ledger history, which is neither a +pass nor a failure. Another orchestrator's holder yields only through queue +priority or the maintainer. + ## Required proof for a PR The policy is [the CI decision](../decisions/ci-utility.md); the commands are diff --git a/scripts/check-pr.ts b/scripts/check-pr.ts index 5b5c31dc30..e2c049383b 100644 --- a/scripts/check-pr.ts +++ b/scripts/check-pr.ts @@ -4,6 +4,7 @@ import { accessSync, constants, readFileSync, statSync } from "node:fs"; import { changedFiles, planChecks, workspaces, type CheckPlan } from "./ci-plan"; import { runCommands, type Command } from "./ci-runner"; import { checkPackages } from "./check-packages"; +import { ensureHostAdmission } from "./host-admission.mjs"; export function localChecks(plan: CheckPlan, full = false, mergeBase?: string, importGraph = false, importGraphWorkers?: number): Command[] { const bun = process.execPath; @@ -152,6 +153,12 @@ if (import.meta.main) { if (print) process.exit(0); requireLocalSandbox(); const chrome = full ? requireRuntimeTools(plan) : undefined; + if (full) { + // Full local suites are for debugging only and run through host admission + // (#2939, #2943), after the cheap prerequisite refusals above. + const admitted = await ensureHostAdmission(all ? "check:pr --all" : "check:pr --full"); + if (admitted !== undefined) process.exit(admitted); + } // Setup/metadata are ordered. Full Bun tests and strict types are the only // independent memory-bounded pair; browser jobs stay sequential to retain // the measured scheduling/isolation behavior and diagnostic artifacts. diff --git a/scripts/host-admission.d.mts b/scripts/host-admission.d.mts new file mode 100644 index 0000000000..97efcf69b2 --- /dev/null +++ b/scripts/host-admission.d.mts @@ -0,0 +1,47 @@ +export const MARKER: "BRAIN_HOST_ADMISSION"; +export const PREEMPTED_EXIT: 75; +export const RED_MAIN_FIX: "red-main-fix"; +export const DEFAULT_GRACE_MS: number; +export function testLedgerFor(pid: number, start: string): string; +export function ledgerDir(env?: Record): string; +export function admissionLimit(env?: Record, cpus?: number): number; +export interface AdmissionEntry { + id: string; + state: "queued" | "holding"; + pid: number; + start: string; + worker: string; + orchestrator: string | null; + priority: "red-main-fix" | "ordinary"; + fixPR: number | null; + label: string; + seq: number; + queuedAt: string; + admittedAt?: string; + child?: { pid: number; start: string }; + preempt?: { reason: string; by: string; at: string; graceMs: number }; +} +export interface AdmissionState { version: 1; seq: number; entries: AdmissionEntry[] } +export function admissionOrder(entries: readonly AdmissionEntry[]): AdmissionEntry[]; +export function readHistory(dir: string): Record[]; +export function withLedger(dir: string, transaction: (state: AdmissionState) => T): Promise; +export interface AdmissionOptions { + env?: Record; + dir?: string; + limit?: number; + worker?: string; + orchestrator?: string; + redMainFix?: string | number; + label?: string; + pollMs?: number; + root?: string; + timingsOut?: string; +} +export function runAdmitted(command: readonly string[], options?: AdmissionOptions): Promise; +export function preempt(slot: string, options?: { env?: Record; dir?: string; orchestrator?: string; reason?: string; graceMs?: number }): + Promise<{ slot: string; reason: string; preempted: true; forced: boolean }>; +export class RefusedError extends Error {} +export function status(options?: { env?: Record; dir?: string }): + Promise<{ ledger: string; limit: number; holders: AdmissionEntry[]; queue: AdmissionEntry[] }>; +export function inheritedAdmission(env?: Record): boolean; +export function ensureHostAdmission(label: string): Promise; diff --git a/scripts/host-admission.mjs b/scripts/host-admission.mjs new file mode 100644 index 0000000000..29c1636007 --- /dev/null +++ b/scripts/host-admission.mjs @@ -0,0 +1,450 @@ +/** + * Host-wide admission for heavy local test commands (#2943). + * + * Separate worktrees on one machine share nothing through the workspace lease + * (`scripts/workspace-lease.mjs`), so five checkouts could start five native + * suites at once and time out together. This ledger admits at most a limited + * number of heavy commands per host; the rest wait in a priority queue instead + * of starting. Its state is durable and only ever changed under a short ledger + * lock by these commands, so a crashed orchestrator or worker leaves nothing an + * ordinary later caller cannot reconcile: dead holders and waiters are pruned + * by process identity on every pass. + * + * node scripts/host-admission.mjs run [--red-main-fix ] [--label ] -- + * node scripts/host-admission.mjs preempt --reason red-main-fix [--grace-ms ] + * node scripts/host-admission.mjs status + * + * Preemption follows the #2938 ruling: only within the caller's own + * orchestrator subtree, and only to admit a waiting red-main fix. A preempted + * run is recorded as `preempted`, which is neither a pass nor a failure. + */ +import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { randomBytes } from "node:crypto"; +import { availableParallelism, constants, tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { inheritWorkspaceLease, liveAncestor, processIdentity } from "./workspace-lease.mjs"; + +/** Inherited by an admitted command, so its nested heavy commands do not queue behind themselves. */ +export const MARKER = "BRAIN_HOST_ADMISSION"; +/** Distinct from a pass (0) and an ordinary failure: EX_TEMPFAIL. */ +export const PREEMPTED_EXIT = 75; +export const RED_MAIN_FIX = "red-main-fix"; +export const DEFAULT_GRACE_MS = 10_000; +const OPAQUE = /^[A-Za-z0-9_-]{1,100}$/; +const script = fileURLToPath(import.meta.url); +const repoRoot = resolve(dirname(script), ".."); +const sleep = ms => new Promise(done => setTimeout(done, ms)); +const now = () => new Date().toISOString(); + +const user = () => typeof process.getuid === "function" ? process.getuid() : "user"; + +/** + * A test process's private ledger. The test preload creates it with the same + * convention, so a descendant whose environment was replaced still finds it + * through its ancestry and never queues behind the host's real heavy commands. + */ +export function testLedgerFor(pid, start) { + return join(tmpdir(), `brain-host-admission-test-${user()}-${pid}-${start}`); +} + +/** This process's ancestors, nearest first (Linux only). */ +function ancestors() { + const found = []; + if (process.platform !== "linux") return found; + let pid = processIdentity(process.pid)?.parent; + for (let depth = 0; pid > 0 && depth < 128; depth++) { + const identity = processIdentity(pid); + if (!identity) break; + found.push({ pid, start: identity.start }); + pid = identity.parent; + } + return found; +} + +/** + * One ledger per host user; worktrees and clones on the machine share it. + * An explicit directory wins, then the nearest ancestor test process's ledger. + */ +export function ledgerDir(env = process.env) { + if (env.BRAIN_HOST_ADMISSION_DIR) return resolve(env.BRAIN_HOST_ADMISSION_DIR); + for (const ancestor of ancestors()) { + const dir = testLedgerFor(ancestor.pid, ancestor.start); + if (existsSync(dir)) return dir; + } + return join(tmpdir(), `brain-host-admission-${user()}`); +} + +/** Heavy suites each use many cores; by default admit one per four CPUs. */ +export function admissionLimit(env = process.env, cpus = availableParallelism()) { + const raw = env.BRAIN_HOST_ADMISSION_LIMIT; + if (raw === undefined || raw === "") return Math.max(1, Math.floor(cpus / 4)); + if (!/^[1-9]\d*$/.test(raw.trim())) throw new Error("BRAIN_HOST_ADMISSION_LIMIT must be a positive integer"); + return Number(raw.trim()); +} + +function opaque(value, name) { + if (value === undefined || value === "") return null; + if (!OPAQUE.test(value)) throw new Error(`${name} must be an opaque ID of letters, digits, '-' or '_'`); + return value; +} + +/** Linux compares process lifetimes, so a reused PID never keeps a slot. */ +function alive(pid, start) { + if (process.platform === "linux") return processIdentity(pid)?.start === start; + try { process.kill(pid, 0); return true; } catch (error) { return error.code === "EPERM"; } +} + +function groupAlive(pgid) { + try { process.kill(-pgid, 0); return true; } catch (error) { return error.code === "EPERM"; } +} + +function signalGroup(pgid, signal) { + try { process.kill(-pgid, signal); } catch (error) { if (error.code !== "ESRCH") throw error; } +} + +const identity = () => processIdentity(process.pid)?.start ?? ""; + +function lockOwnerStale(lock) { + let owner; + try { owner = readFileSync(join(lock, "owner"), "utf8"); } + catch { + // The owner writes its identity right after mkdir; give that gap time. + try { return Date.now() - statSync(lock).mtimeMs > 2_000; } catch { return false; } + } + const [pid, start] = owner.split(" "); + return !alive(Number(pid), start ?? ""); +} + +/** Only one caller removes a dead owner's lock; the guard serializes stealers. */ +function stealStaleLock(lock) { + const guard = `${lock}.steal`; + try { mkdirSync(guard); } + catch (error) { + if (error.code !== "EEXIST") throw error; + try { if (Date.now() - statSync(guard).mtimeMs > 5_000) rmSync(guard, { recursive: true, force: true }); } catch { /* raced */ } + return; + } + try { if (lockOwnerStale(lock)) rmSync(lock, { recursive: true, force: true }); } + finally { rmSync(guard, { recursive: true, force: true }); } +} + +function readState(dir) { + try { + const state = JSON.parse(readFileSync(join(dir, "state.json"), "utf8")); + if (state?.version === 1 && Number.isSafeInteger(state.seq) && Array.isArray(state.entries)) return state; + } catch (error) { if (error.code !== "ENOENT" && !(error instanceof SyntaxError)) throw error; } + return { version: 1, seq: 0, entries: [] }; +} + +function writeState(dir, state) { + const path = join(dir, "state.json"), staged = `${path}.${process.pid}.${randomBytes(4).toString("hex")}`; + writeFileSync(staged, JSON.stringify(state, null, 2) + "\n", { mode: 0o600 }); + renameSync(staged, path); +} + +export function history(dir, event) { + appendFileSync(join(dir, "history.jsonl"), JSON.stringify({ at: now(), ...event }) + "\n", { mode: 0o600 }); +} + +export function readHistory(dir) { + try { return readFileSync(join(dir, "history.jsonl"), "utf8").split("\n").filter(Boolean).map(line => JSON.parse(line)); } + catch (error) { if (error.code === "ENOENT") return []; throw error; } +} + +/** Run a synchronous ledger transaction under the host-wide lock. */ +export async function withLedger(dir, transaction) { + mkdirSync(dir, { recursive: true, mode: 0o700 }); + const lock = join(dir, "ledger.lock"), me = `${process.pid} ${identity()}`; + for (let attempt = 0; ; attempt++) { + try { mkdirSync(lock); writeFileSync(join(lock, "owner"), me); break; } + catch (error) { if (error.code !== "EEXIST") throw error; } + if (lockOwnerStale(lock)) stealStaleLock(lock); + if (attempt > 6_000) throw new Error("The host admission ledger lock stayed unavailable"); + await sleep(5 + Math.floor(Math.random() * 10)); + } + try { + const state = readState(dir); + const result = transaction(state); + writeState(dir, state); + return result; + } finally { rmSync(lock, { recursive: true, force: true }); } +} + +/** + * Forget dead waiters and reclaim dead holders. A holder whose wrapper died + * while its detached command group still runs keeps the slot until that group + * has been killed and is gone, so the slot is never handed out twice. + */ +export function prune(state, dir) { + state.entries = state.entries.filter(entry => { + if (alive(entry.pid, entry.start)) return true; + if (entry.state === "holding" && entry.child && groupAlive(entry.child.pid)) { + signalGroup(entry.child.pid, "SIGKILL"); + if (groupAlive(entry.child.pid)) return true; + } + history(dir, { kind: entry.state === "holding" ? (entry.preempt ? "preempted" : "reclaimed") : "abandoned", + slot: entry.id, worker: entry.worker, orchestrator: entry.orchestrator, priority: entry.priority }); + return false; + }); +} + +const rank = entry => entry.priority === RED_MAIN_FIX ? 0 : 1; + +/** Red-main fixes go ahead of every ordinary waiter; otherwise arrival order. */ +export function admissionOrder(entries) { + return entries.filter(entry => entry.state === "queued").sort((a, b) => rank(a) - rank(b) || a.seq - b.seq); +} + +function tryAdmit(state, dir, id, limit) { + prune(state, dir); + const entry = state.entries.find(candidate => candidate.id === id); + if (!entry) return { lost: true }; + const holders = state.entries.filter(candidate => candidate.state === "holding"); + const order = admissionOrder(state.entries), position = order.indexOf(entry); + if (position < limit - holders.length) { + entry.state = "holding"; entry.admittedAt = now(); + history(dir, { kind: "admitted", slot: id, worker: entry.worker, orchestrator: entry.orchestrator, priority: entry.priority }); + return { admitted: true }; + } + return { admitted: false, position: position + 1, queued: order.length, limit, + holders: holders.map(holder => `${holder.id} (${holder.label}, worker ${holder.worker}, ${holder.priority})`) }; +} + +/** Record a wait boundary through the shared coordination recorder. */ +async function recordWait(kind, { worker, task, timingsOut, root, ledger }) { + const { spawn } = await import("node:child_process"); + const dir = join(ledger, "events"); + try { + mkdirSync(dir, { recursive: true }); + const file = join(dir, `${task}-${kind}.json`); + writeFileSync(file, JSON.stringify({ kind, worker, task, reason: "other" })); + const bun = process.versions.bun ? process.execPath : "bun"; + const code = await new Promise(done => { + const child = spawn(bun, [join(root, "scripts/ci-timings.ts"), "record", "--event", file, "--out", timingsOut], + { stdio: ["ignore", "ignore", "inherit"] }); + child.once("error", () => done(1)); + child.once("exit", status => done(status ?? 1)); + }); + rmSync(file, { force: true }); + if (code !== 0) console.error(`Host admission could not record ${kind}; the wait itself is unaffected.`); + } catch (error) { console.error(`Host admission could not record ${kind}: ${error.message}`); } +} + +function exitCode(code, signal) { + return signal ? 128 + (constants.signals[signal] ?? 0) : code ?? 1; +} + +/** Wait for a slot, run the command in its own process group, then release. */ +export async function runAdmitted(command, options = {}) { + if (!command.length) throw new Error("Host admission needs a command after --"); + const env = options.env ?? process.env; + const dir = options.dir ?? ledgerDir(env), limit = options.limit ?? admissionLimit(env); + const worker = opaque(options.worker ?? env.BRAIN_WORKER_ID, "Worker ID") ?? `host-${process.pid}`; + const orchestrator = opaque(options.orchestrator ?? env.BRAIN_ORCHESTRATOR_ID, "Orchestrator ID"); + const fix = options.redMainFix ?? env.BRAIN_RED_MAIN_FIX; + if (fix !== undefined && fix !== "" && !/^[1-9]\d*$/.test(String(fix))) throw new Error("A red-main fix is declared by its PR number"); + const fixPR = fix ? Number(fix) : null, priority = fixPR ? RED_MAIN_FIX : "ordinary"; + const label = String(options.label ?? command.join(" ")).slice(0, 120); + const pollMs = options.pollMs ?? 500, root = options.root ?? repoRoot; + const timingsOut = resolve(options.timingsOut ?? join(root, "tmp", "ci-timings")); + const start = identity(); + let id, child, cancelled; + await withLedger(dir, state => { + state.seq += 1; + id = `h${state.seq}-${randomBytes(4).toString("hex")}`; + state.entries.push({ id, state: "queued", pid: process.pid, start, worker, orchestrator, priority, fixPR, label, seq: state.seq, queuedAt: now() }); + history(dir, { kind: "queued", slot: id, worker, orchestrator, priority, fixPR }); + }); + const release = async kind => withLedger(dir, state => { + const entry = state.entries.find(candidate => candidate.id === id); + state.entries = state.entries.filter(candidate => candidate !== entry); + const preempted = Boolean(entry?.preempt); + history(dir, { kind: preempted ? "preempted" : kind, slot: id, worker, orchestrator, priority, + ...(preempted ? { reason: entry.preempt.reason, by: entry.preempt.by } : {}) }); + return preempted; + }); + const signals = ["SIGINT", "SIGTERM", "SIGHUP"]; + const listeners = signals.map(signal => () => { + if (child?.pid) signalGroup(child.pid, signal); + else cancelled = signal; + }); + signals.forEach((signal, index) => process.on(signal, listeners[index])); + const task = `admission-${id}`; + try { + let waited = false, last = ""; + for (;;) { + if (cancelled) { await release("cancelled"); return exitCode(null, cancelled); } + const result = await withLedger(dir, state => { + const attempt = tryAdmit(state, dir, id, limit); + if (attempt.lost) state.entries.push({ id, state: "queued", pid: process.pid, start, worker, orchestrator, priority, fixPR, label, seq: ++state.seq, queuedAt: now() }); + return attempt; + }); + if (result.admitted) break; + if (result.lost) continue; + if (!waited) { waited = true; await recordWait("wait-started", { worker, task, timingsOut, root, ledger: dir }); } + const line = `Waiting for a host admission slot (${result.limit} on this host): position ${result.position} of ${result.queued}; holders: ${result.holders.join(", ") || "none"}.`; + if (line !== last) { console.error(line); last = line; } + await sleep(pollMs); + } + if (waited) await recordWait("wait-finished", { worker, task, timingsOut, root, ledger: dir }); + if (cancelled) { await release("cancelled"); return exitCode(null, cancelled); } + const { spawn } = await import("node:child_process"); + // Pass the workspace lease's descriptor on: a command in a nested user + // namespace cannot prove its inherited lease through /proc. + child = spawn(command[0], command.slice(1), inheritWorkspaceLease({ stdio: ["inherit", "inherit", "inherit"], + detached: process.platform !== "win32", env: { ...env, [MARKER]: JSON.stringify({ slot: id, pid: process.pid, start, dir }) } }, "inherit")); + const exited = new Promise(done => { + child.once("error", () => done(127)); + child.once("exit", (code, signal) => done(exitCode(code, signal))); + }); + if (child.pid) { + const pending = await withLedger(dir, state => { + const entry = state.entries.find(candidate => candidate.id === id); + if (entry) entry.child = { pid: child.pid, start: processIdentity(child.pid)?.start ?? "" }; + return entry?.preempt; + }); + // A preemption requested before the group existed is delivered now. + if (pending) signalGroup(child.pid, "SIGTERM"); + } + const code = await exited; + if (child.pid) { + const preempt = await withLedger(dir, state => state.entries.find(candidate => candidate.id === id)?.preempt); + if (preempt) { + // Let the group's cleanup finish within the preemption's grace period. + const deadline = Date.parse(preempt.at) + preempt.graceMs; + while (groupAlive(child.pid) && Date.now() < deadline) await sleep(25); + } + signalGroup(child.pid, "SIGKILL"); + while (groupAlive(child.pid)) await sleep(10); + } + if (await release("released")) { + console.error(`Host admission slot ${id} was preempted to admit a red-main fix; this run neither passed nor failed.`); + return PREEMPTED_EXIT; + } + return code; + } finally { + signals.forEach((signal, index) => process.off(signal, listeners[index])); + } +} + +/** + * Cancel a holder in the caller's own orchestrator subtree so a waiting + * red-main fix can start. Its group gets SIGTERM, then SIGKILL after the grace + * period; the slot is released only after the group has gone. + */ +export async function preempt(slot, options = {}) { + const env = options.env ?? process.env, dir = options.dir ?? ledgerDir(env); + const orchestrator = opaque(options.orchestrator ?? env.BRAIN_ORCHESTRATOR_ID, "Orchestrator ID"); + const graceMs = options.graceMs ?? DEFAULT_GRACE_MS, reason = options.reason; + if (reason !== RED_MAIN_FIX) throw new RefusedError(`Preemption is only permitted to admit a red-main fix (--reason ${RED_MAIN_FIX})`); + if (!orchestrator) throw new RefusedError("Preemption requires the caller's orchestrator ID (BRAIN_ORCHESTRATOR_ID or --orchestrator)"); + if (!Number.isSafeInteger(graceMs) || graceMs < 0) throw new Error("Grace period must be a non-negative integer of milliseconds"); + const outcome = await withLedger(dir, state => { + prune(state, dir); + const entry = state.entries.find(candidate => candidate.id === slot && candidate.state === "holding"); + if (!entry) return { refused: `Slot ${slot} is not held` }; + if (entry.orchestrator !== orchestrator) return { refused: `Slot ${slot} is outside the caller's orchestrator subtree; it yields only through queue priority or the maintainer` }; + if (!state.entries.some(candidate => candidate.state === "queued" && candidate.priority === RED_MAIN_FIX)) return { refused: "No red-main fix is waiting for admission" }; + if (!entry.preempt) { + entry.preempt = { reason, by: orchestrator, at: now(), graceMs }; + history(dir, { kind: "preempt-requested", slot, orchestrator, reason, graceMs }); + } + return { child: entry.child }; + }); + if (outcome.refused) throw new RefusedError(outcome.refused); + if (outcome.child) signalGroup(outcome.child.pid, "SIGTERM"); + const deadline = Date.now() + graceMs; + let forced = false; + for (;;) { + const entry = await withLedger(dir, state => { prune(state, dir); return state.entries.find(candidate => candidate.id === slot); }); + if (!entry) return { slot, reason, preempted: true, forced }; + if (Date.now() >= deadline && entry.child && groupAlive(entry.child.pid)) { signalGroup(entry.child.pid, "SIGKILL"); forced = true; } + if (Date.now() >= deadline + 30_000) throw new Error(`Slot ${slot} was signalled but its holder has not released it`); + await sleep(25); + } +} + +export class RefusedError extends Error {} + +export async function status(options = {}) { + const dir = options.dir ?? ledgerDir(options.env); + return withLedger(dir, state => { + prune(state, dir); + return { ledger: dir, limit: admissionLimit(options.env), holders: state.entries.filter(entry => entry.state === "holding"), + queue: admissionOrder(state.entries) }; + }); +} + +/** + * True when an ancestor already holds a slot for this command tree: through + * the inherited marker, or, for a descendant whose environment was replaced, + * through a holder in the ledger that is one of its live ancestors. + */ +export function inheritedAdmission(env = process.env) { + try { + const held = JSON.parse(env[MARKER] || "null"); + if (held && Number.isSafeInteger(held.pid) && typeof held.start === "string" && + (process.platform === "linux" ? liveAncestor(held.pid, held.start) : alive(held.pid, held.start))) return true; + } catch { /* A malformed marker grants nothing; the ledger may still. */ } + if (process.platform !== "linux") return false; + return readState(ledgerDir(env)).entries.some(entry => entry.state === "holding" && liveAncestor(entry.pid, entry.start)); +} + +/** + * Re-enter this heavy command through `run`, unless an ancestor holds a slot. + * Returns the admitted command's exit code, or undefined to continue inline. + */ +export async function ensureHostAdmission(label) { + if (inheritedAdmission()) return; + const { spawn } = await import("node:child_process"); + let child, pending; + const signals = ["SIGINT", "SIGTERM", "SIGHUP"]; + const listeners = signals.map(signal => () => { if (child) child.kill(signal); else pending = signal; }); + signals.forEach((signal, index) => process.on(signal, listeners[index])); + try { + child = spawn(process.execPath, [script, "run", "--label", label, "--", process.execPath, ...process.execArgv, ...process.argv.slice(1)], + inheritWorkspaceLease({ stdio: ["inherit", "inherit", "inherit"] }, "inherit")); + if (pending) child.kill(pending); + return await new Promise((done, reject) => { + child.once("error", reject); + child.once("exit", (code, signal) => done(exitCode(code, signal))); + }); + } finally { signals.forEach((signal, index) => process.off(signal, listeners[index])); } +} + +function parse(args) { + const options = {}, rest = []; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === "--") { options.command = args.slice(i + 1); break; } + const value = () => { if (i + 1 >= args.length) throw new Error(`${arg} needs a value`); return args[++i]; }; + if (arg === "--label") options.label = value(); + else if (arg === "--red-main-fix") options.redMainFix = value(); + else if (arg === "--worker") options.worker = value(); + else if (arg === "--orchestrator") options.orchestrator = value(); + else if (arg === "--reason") options.reason = value(); + else if (arg === "--grace-ms") options.graceMs = Number(value()); + else if (arg === "--poll-ms") options.pollMs = Number(value()); + else if (arg === "--timings-out") options.timingsOut = value(); + else if (arg.startsWith("-")) throw new Error(`Unknown option ${arg}`); + else rest.push(arg); + } + return { options, rest }; +} + +const usage = "usage: host-admission.mjs run [--red-main-fix ] [--label ] -- | preempt --reason red-main-fix [--grace-ms ] | status"; + +if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) { + try { + const [mode, ...args] = process.argv.slice(2); + const { options, rest } = parse(args); + if (mode === "run" && !rest.length) process.exit(await runAdmitted(options.command ?? [], options)); + else if (mode === "preempt" && rest.length === 1 && !options.command) console.log(JSON.stringify(await preempt(rest[0], options))); + else if (mode === "status" && !rest.length && !options.command) console.log(JSON.stringify(await status(), null, 2)); + else throw new Error(usage); + } catch (error) { + console.error(error instanceof Error ? error.message : String(error)); + process.exit(error instanceof RefusedError ? 2 : 1); + } +} diff --git a/scripts/test-network-preload.ts b/scripts/test-network-preload.ts index e797298f60..afa60694a5 100644 --- a/scripts/test-network-preload.ts +++ b/scripts/test-network-preload.ts @@ -1,12 +1,25 @@ import { afterAll, afterEach } from "bun:test"; import { cleanupCliUtilities } from "../packages/core/tests/cli-harness"; import { installNetworkGuard } from "./test-network-guard"; -import { resolve } from "node:path"; -import { ensureWorkspaceLease, workspaceTestAccess } from "./workspace-lease.mjs"; +import { join, resolve } from "node:path"; +import { mkdirSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { ensureWorkspaceLease, processIdentity, workspaceTestAccess } from "./workspace-lease.mjs"; const guard = installNetworkGuard(); const coordinated = await ensureWorkspaceLease(resolve(import.meta.dir, ".."), workspaceTestAccess(), "test"); if (coordinated !== undefined) process.exit(coordinated); +// Commands a test spawns queue in a ledger private to this test process, never +// behind the host's real heavy commands (#2943). The path is testLedgerFor's +// convention in scripts/host-admission.mjs, so a descendant whose environment +// was replaced finds it through its ancestry. A test exercising the host ledger +// names its own directory; an admitted caller's descendants inherit its slot. +// One flat entry, removed in afterAll, so a test asserting an empty TMPDIR +// after its child exits sees nothing left behind. +const privateAdmission = join(tmpdir(), + `brain-host-admission-test-${process.getuid?.() ?? "user"}-${process.pid}-${processIdentity(process.pid)?.start ?? "0"}`); +mkdirSync(privateAdmission, { mode: 0o700 }); +process.env.BRAIN_HOST_ADMISSION_DIR = privateAdmission; afterEach(() => guard.assertNoEscapes()); // A preload hook runs after all files; a hook in the cached helper would run // after its first importing file. Bun test does not run the ordinary exit hook. @@ -15,5 +28,6 @@ afterAll(() => { guard.assertNoEscapes(); } finally { cleanupCliUtilities(); + rmSync(privateAdmission, { recursive: true, force: true }); } }); diff --git a/scripts/test.ts b/scripts/test.ts index 46e160dfe8..e0d22f756b 100644 --- a/scripts/test.ts +++ b/scripts/test.ts @@ -17,12 +17,14 @@ */ import { constants } from "node:os"; -import { join, resolve } from "node:path"; +import { isAbsolute, join, resolve } from "node:path"; import { realpathSync } from "node:fs"; import { invocationChild } from "./test-invocation-child"; import { runtimeBuildSelection } from "./runtime-test-builds"; import { acceptsSpeechDelegation, clearInvocation, prepareCopiedInvocation, prepareInvocation, takePreparedTree } from "./test-invocation"; import { ensureWorkspaceLease, workspaceTestAccess } from "./workspace-lease.mjs"; +import { ensureHostAdmission } from "./host-admission.mjs"; +import { FILE_COST_SECONDS } from "./test-shards"; /** What runs when the caller names no path. */ export const DEFAULT_ROOTS: readonly string[] = ["packages", "tests"]; @@ -125,6 +127,33 @@ export function testArgv(args: readonly string[]): string[] { return testPaths(args).length ? [...args] : [...DEFAULT_PATH_ARGS, ...args]; } +/** A measured file at or over this many seconds is a heavy local command on its own (#2943). */ +export const HEAVY_TEST_FILE_SECONDS = 30; + +/** + * Why a selection needs host admission, or undefined for a focused run: the + * integrated default suite, runtime-host and native suites, and any selected + * file whose measured cost reaches HEAVY_TEST_FILE_SECONDS. Paths match the + * way runtimeBuildSelection matches them. + */ +export function heavyTestReason(root: string, cwd: string, args: readonly string[], + costs: Readonly> = FILE_COST_SECONDS): string | undefined { + const paths = testPaths(args); + if (!paths.length) return "integrated suite"; + if (runtimeBuildSelection(root, cwd, paths).length) return "runtime-host tests"; + if (paths.some(path => /(?:^|\/)native-proof(?:\/|$)|\.native\./.test(path))) return "native tests"; + const selects = (file: string) => paths.some(path => { + const absolute = join(root, file); + if (isAbsolute(path) || path.startsWith(".")) { + const target = resolve(cwd, path); + return absolute === target || absolute.startsWith(`${target}/`); + } + return absolute.includes(path); + }); + const long = Object.entries(costs).find(([file, seconds]) => seconds >= HEAVY_TEST_FILE_SECONDS && selects(file)); + return long ? `long test file ${long[0]}` : undefined; +} + if (import.meta.main) { const coordinated = await ensureWorkspaceLease(resolve(import.meta.dir, ".."), workspaceTestAccess()); if (coordinated !== undefined) process.exit(coordinated); @@ -159,6 +188,13 @@ if (import.meta.main) { } args = forwarded; argv = testArgv(args); + const heavy = help ? undefined : heavyTestReason(resolve(import.meta.dir, ".."), process.cwd(), args); + // Inside the workspace lease: a queued command never holds a host slot + // while it waits for its own checkout's output. + if (heavy) { + const admitted = await ensureHostAdmission(`bun run test (${heavy})`); + if (admitted !== undefined) process.exit(admitted); + } if (balanced.length) { if (balanced.length !== 1 || argv.length === args.length || args.some((arg) => arg.startsWith("--shard") || arg.startsWith("--cwd"))) { diff --git a/scripts/unit-workers.ts b/scripts/unit-workers.ts index faf960a393..a417d3a1ab 100644 --- a/scripts/unit-workers.ts +++ b/scripts/unit-workers.ts @@ -4,6 +4,7 @@ import { createHash, randomUUID } from "node:crypto"; import { availableParallelism, tmpdir, totalmem } from "node:os"; import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path"; import { runCommands } from "./ci-runner"; +import { ensureHostAdmission } from "./host-admission.mjs"; import { balanceTests, FILE_COST_SECONDS } from "./test-shards"; import { validateChangedUnitReports, validateUnitReports } from "./unit-proof-report"; import { captureUnitInputs } from "./unit-worker-inputs"; @@ -430,6 +431,10 @@ async function bootstrapPreparedTree(root: string, files: readonly string[], chr } if (import.meta.main) { + // The queue is one heavy command: it holds a single host slot (#2943) that + // its parallel workers inherit, rather than queueing them behind each other. + const admitted = await ensureHostAdmission("unit worker queue"); + if (admitted !== undefined) process.exit(admitted); try { const root = resolve(import.meta.dir, ".."); const options: UnitWorkerOptions = {}, files: string[] = []; diff --git a/scripts/visual.mjs b/scripts/visual.mjs index d7a60e902c..4a93fdb774 100644 --- a/scripts/visual.mjs +++ b/scripts/visual.mjs @@ -119,6 +119,17 @@ if (inside) { const uid = typeof process.getuid === "function" ? process.getuid() : 0; const gid = typeof process.getgid === "function" ? process.getgid() : 0; +// Browser proof is a heavy local command: separate worktrees share the host's +// admission slots (#2943). The container cannot see the host ledger, so the +// host side holds the slot for the whole container run. +// Loaded here, not statically: the container never imports it, so it is not +// part of the pinned native diagram source. +{ + const { ensureHostAdmission } = await import("./host-admission.mjs"); + const admitted = await ensureHostAdmission(`browser proof (${projects.join(", ")})`); + if (admitted !== undefined) process.exit(admitted); +} + // Execution bootstrap owns acquisition. Metadata lookup and the network-disabled // native producer never pull; both consumers launch this exact manifest digest. const inspectImage = () => spawnSync("docker", ["image", "inspect", IMAGE, "--format", "{{json .RepoDigests}}"], { encoding: "utf8" }); diff --git a/tests/experiment-tier.test.ts b/tests/experiment-tier.test.ts index 59a279ab57..2fad53a575 100644 --- a/tests/experiment-tier.test.ts +++ b/tests/experiment-tier.test.ts @@ -17,7 +17,7 @@ import { const ROOT = join(import.meta.dir, ".."); const SCRIPTS = ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-experiments.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", - "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]; + "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]; const passing = (name: string) => `import { expect, test } from "bun:test";\ntest(${JSON.stringify(name)}, () => expect(1).toBe(1));\n`; diff --git a/tests/helpers/test-invocation-fixture.ts b/tests/helpers/test-invocation-fixture.ts index ac63308c7c..d1dc673fb2 100644 --- a/tests/helpers/test-invocation-fixture.ts +++ b/tests/helpers/test-invocation-fixture.ts @@ -10,7 +10,7 @@ export function invocationFixture(parent = tmpdir()) { write("bun.lock", "{}\n"); write(".gitignore", "node_modules/\npackages/*/dist/\ntmp/\n"); write("tsconfig.json", JSON.stringify({ compilerOptions: { target: "ES2019", module: "ESNext", moduleResolution: "Bundler", types: [], skipLibCheck: true } })); - for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "test.ts", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-network-guard.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { + for (const file of ["build.ts", "clean.ts", "build-execution.ts", "build-receipt.ts", "build-repeat-observation.ts", "bin-modes.ts", "publishable-packages.ts", "workspace-lease.mjs", "host-admission.mjs", "test.ts", "test-shards.ts", "test-shard-costs.json", "test-invocation.ts", "test-invocation-child.ts", "runtime-test-builds.ts", "test-network-preload.ts", "test-network-guard.ts", "test-network-child-preload.ts", "unit-worker-entry.sh"]) { write(`scripts/${file}`, readFileSync(join(source, "scripts", file), "utf8")); } for (const file of ["packages/core/tests/cli-harness.ts", "packages/ui-react/tests/fixtures/runtime-package-build.ts", "packages/ui-react/tests/fixtures/runtime-hook-phases.ts"]) write(file, readFileSync(join(source, file), "utf8")); diff --git a/tests/helpers/unit-worker-fixture.ts b/tests/helpers/unit-worker-fixture.ts index e2b73ffd28..82031daf4d 100644 --- a/tests/helpers/unit-worker-fixture.ts +++ b/tests/helpers/unit-worker-fixture.ts @@ -66,7 +66,7 @@ const stop=Date.now()+5000;while((!existsSync(join(shared,"built-1"))||!existsSy ${options.failBuild ? "process.exit(7);" : ""} mkdirSync("dist",{recursive:true});writeFileSync("dist/lease.json",JSON.stringify({lease:JSON.parse(process.env.BRAIN_WORKSPACE_LEASE),nonce:process.env.BRAIN_TEST_INVOCATION_NONCE}));writeFileSync("dist/ready.txt","Odysseus builds the raft.");receipt.packageEnd("raft",true);receipt.finish(0);\n`); for (const file of ["scripts/test.ts", "scripts/runtime-test-builds.ts", "scripts/test-invocation.ts", "scripts/test-invocation-child.ts", "scripts/publishable-packages.ts", - "scripts/workspace-lease.mjs", "scripts/test-network-preload.ts", "scripts/test-network-child-preload.ts", "scripts/test-network-guard.ts", "packages/core/tests/cli-harness.ts"]) { + "scripts/workspace-lease.mjs", "scripts/host-admission.mjs", "scripts/test-shards.ts", "scripts/test-shard-costs.json", "scripts/test-network-preload.ts", "scripts/test-network-child-preload.ts", "scripts/test-network-guard.ts", "packages/core/tests/cli-harness.ts"]) { write(file, readFileSync(join(source, file), "utf8")); } const files = ["odysseus", "penelope"].map(name => `tests/${name}.test.ts`); diff --git a/tests/host-admission.test.ts b/tests/host-admission.test.ts new file mode 100644 index 0000000000..d70bd35d12 --- /dev/null +++ b/tests/host-admission.test.ts @@ -0,0 +1,247 @@ +// Host-wide admission for heavy local commands (#2943): separate worktrees on +// one machine share a limited number of slots instead of timing out together. +import { afterEach, describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { admissionLimit, admissionOrder, PREEMPTED_EXIT, readHistory, testLedgerFor, type AdmissionEntry } from "../scripts/host-admission.mjs"; +import { processIdentity } from "../scripts/workspace-lease.mjs"; +import { heavyTestReason, HEAVY_TEST_FILE_SECONDS } from "../scripts/test"; + +const ROOT = resolve(import.meta.dir, ".."); +const SCRIPT = join(ROOT, "scripts/host-admission.mjs"); +const scratch: string[] = []; +const children: Bun.Subprocess[] = []; + +afterEach(() => { + for (const child of children.splice(0)) { try { child.kill("SIGKILL"); } catch { /* gone */ } } + // A killed wrapper leaves its detached command group for the next ledger + // pass to reclaim; a failed test must not leave that group running. + for (const dir of scratch) for (const entry of entries(join(dir, "ledger"))) { + if (entry.child) { try { process.kill(-entry.child.pid, "SIGKILL"); } catch { /* gone */ } } + } + for (const dir of scratch.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +function fixture() { + const dir = mkdtempSync(join(tmpdir(), "odysseus-host-admission-")); + scratch.push(dir); + const ledger = join(dir, "ledger"), timings = join(dir, "timings"); + // Two separate checkouts of Ithaca's harbour plan share one host. + for (const name of ["ithaca", "ogygia"]) mkdirSync(join(dir, name)); + return { dir, ledger, timings }; +} + +/** Never inherit the caller's slot, worker or orchestrator identity. */ +function env(ledger: string, extra: Record = {}) { + return { PATH: process.env.PATH!, HOME: process.env.HOME ?? tmpdir(), BRAIN_HOST_ADMISSION_DIR: ledger, BRAIN_HOST_ADMISSION_LIMIT: "1", ...extra }; +} + +function admit(cwd: string, ledger: string, timings: string, command: string, extra: Record = {}, flags: string[] = []) { + const child = Bun.spawn([process.execPath, SCRIPT, "run", "--poll-ms", "20", "--timings-out", timings, ...flags, "--", "sh", "-c", command], + { cwd, env: env(ledger, extra), stdout: "pipe", stderr: "pipe" }); + children.push(child); + const output = Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text()]).then(([out, err]) => out + err); + return { child, output }; +} + +function entries(ledger: string): AdmissionEntry[] { + try { return JSON.parse(readFileSync(join(ledger, "state.json"), "utf8")).entries; } catch { return []; } +} + +async function until(condition: () => boolean, what: string, ms = 10_000) { + const deadline = Date.now() + ms; + while (!condition()) { + if (Date.now() > deadline) throw new Error(`Timed out waiting for ${what}`); + await Bun.sleep(10); + } +} + +const holding = (ledger: string) => entries(ledger).filter(entry => entry.state === "holding" && entry.child); +const queued = (ledger: string) => entries(ledger).filter(entry => entry.state === "queued"); + +function alive(pid: number) { + try { process.kill(pid, 0); return true; } catch { return false; } +} + +describe("host admission ledger", () => { + test("with the limit at 1, heavy commands from two worktrees run one after the other and neither times out", async () => { + const { dir, ledger, timings } = fixture(); + const log = join(dir, "log"); + // Each command fails if another is running, and has its own deadline. + const heavy = (name: string) => `if ! mkdir ${dir}/running 2>/dev/null; then echo OVERLAP-${name} >> ${log}; exit 9; fi; ` + + `echo start-${name} >> ${log}; sleep 0.4; echo end-${name} >> ${log}; rmdir ${dir}/running`; + const first = admit(join(dir, "ithaca"), ledger, timings, heavy("ithaca")); + await until(() => holding(ledger).length === 1, "the first holder"); + const second = admit(join(dir, "ogygia"), ledger, timings, heavy("ogygia")); + const deadline = Bun.sleep(8_000).then(() => "timed out"); + expect(await Promise.race([Promise.all([first.child.exited, second.child.exited]), deadline])).toEqual([0, 0]); + expect(readFileSync(log, "utf8").trim().split("\n")).toEqual(["start-ithaca", "end-ithaca", "start-ogygia", "end-ogygia"]); + const waiting = await second.output; + expect(waiting).toContain("Waiting for a host admission slot (1 on this host): position 1 of 1; holders: h1-"); + expect(waiting).toContain("worker host-"); + + // The wait is recorded as one wait-started/wait-finished pair. + const events = readdirSync(timings).filter(name => name.startsWith("event-")) + .map(name => JSON.parse(readFileSync(join(timings, name), "utf8"))) + .sort((a, b) => Date.parse(a.at) - Date.parse(b.at)); + expect(events.map(event => event.kind)).toEqual(["wait-started", "wait-finished"]); + expect(new Set(events.map(event => `${event.worker}/${event.task}/${event.reason}`)).size).toBe(1); + expect(events[0].reason).toBe("other"); + expect(events[0].task).toMatch(/^admission-h2-/); + expect(entries(ledger)).toEqual([]); + }); + + test("with no orchestrator, the host slots still limit concurrent heavy commands", async () => { + const { dir, ledger, timings } = fixture(); + const marks = join(dir, "marks"); + mkdirSync(marks); + const runs = ["a", "b", "c"].map(name => admit(join(dir, "ithaca"), ledger, timings, + `touch ${marks}/${name}; n=$(ls ${marks} | wc -l); echo $n > ${dir}/peak-${name}; sleep 0.3; rm ${marks}/${name}`, + { BRAIN_HOST_ADMISSION_LIMIT: "2" })); + expect(await Promise.all(runs.map(run => run.child.exited))).toEqual([0, 0, 0]); + const peaks = ["a", "b", "c"].map(name => Number(readFileSync(join(dir, `peak-${name}`), "utf8"))); + expect(Math.max(...peaks)).toBeLessThanOrEqual(2); + expect(readHistory(ledger).filter(event => event.kind === "admitted").every(event => event.orchestrator === null)).toBe(true); + }); + + test("a crashed holder's slot is reclaimed, including its orphaned command group", async () => { + const { dir, ledger, timings } = fixture(); + const holder = admit(join(dir, "ithaca"), ledger, timings, `echo $$ > ${dir}/orphan; exec sleep 30`); + await until(() => holding(ledger).length === 1 && existsSync(join(dir, "orphan")), "the holder"); + const orphan = Number(readFileSync(join(dir, "orphan"), "utf8")); + holder.child.kill("SIGKILL"); + await holder.child.exited; + expect(alive(orphan), "the detached command survives its killed wrapper").toBe(true); + const next = admit(join(dir, "ogygia"), ledger, timings, "echo PENELOPE_ADMITTED"); + expect(await Promise.race([next.child.exited, Bun.sleep(8_000).then(() => "blocked")])).toBe(0); + expect(await next.output).toContain("PENELOPE_ADMITTED"); + expect(alive(orphan), "reclaiming the slot stops the orphaned group").toBe(false); + expect(readHistory(ledger).map(event => event.kind)).toContain("reclaimed"); + }); + + test("a red-main fix queued later is admitted ahead of an ordinary waiter", async () => { + const { dir, ledger, timings } = fixture(); + const log = join(dir, "log"); + const holder = admit(join(dir, "ithaca"), ledger, timings, `while [ ! -e ${dir}/release ]; do sleep 0.02; done; echo holder >> ${log}`); + await until(() => holding(ledger).length === 1, "the holder"); + const ordinary = admit(join(dir, "ithaca"), ledger, timings, `echo ordinary >> ${log}`); + await until(() => queued(ledger).length === 1, "the ordinary waiter"); + const fix = admit(join(dir, "ogygia"), ledger, timings, `echo fix >> ${log}`, { BRAIN_RED_MAIN_FIX: "42" }); + await until(() => queued(ledger).length === 2, "the fix waiter"); + expect(admissionOrder(entries(ledger)).map(entry => entry.priority)).toEqual(["red-main-fix", "ordinary"]); + // The running holder is not preempted by priority alone. + expect(holding(ledger)).toHaveLength(1); + Bun.write(join(dir, "release"), ""); + expect(await Promise.all([holder.child.exited, ordinary.child.exited, fix.child.exited])).toEqual([0, 0, 0]); + expect(readFileSync(log, "utf8").trim().split("\n")).toEqual(["holder", "fix", "ordinary"]); + expect(readHistory(ledger).find(event => event.kind === "queued" && event.priority === "red-main-fix")?.fixPR).toBe(42); + }); + + test("preemption lets the holder's cleanup finish before the slot is reassigned, and records preempted", async () => { + const { dir, ledger, timings } = fixture(); + const crew = { BRAIN_ORCHESTRATOR_ID: "odysseus", BRAIN_WORKER_ID: "eurylochus" }; + // The holder's cleanup (a stand-in for unmounting and removing a tmpfs) + // takes a while and writes a marker when it is done. + const holder = admit(join(dir, "ithaca"), ledger, timings, + // The command exits at once and leaves the cleanup to another group member. + `trap '(sleep 0.3; echo cleaned > ${dir}/cleanup) & exit 143' TERM; while true; do sleep 0.02; done`, crew); + await until(() => holding(ledger).length === 1, "the holder"); + const slot = holding(ledger)[0]!.id; + const fix = admit(join(dir, "ogygia"), ledger, timings, `test -e ${dir}/cleanup && echo FIX_AFTER_CLEANUP`, { BRAIN_RED_MAIN_FIX: "7" }); + await until(() => queued(ledger).length === 1, "the fix waiter"); + const preempt = Bun.spawnSync([process.execPath, SCRIPT, "preempt", slot, "--reason", "red-main-fix", "--grace-ms", "5000"], + { env: env(ledger, { BRAIN_ORCHESTRATOR_ID: "odysseus" }), stdout: "pipe", stderr: "pipe" }); + expect(preempt.exitCode, preempt.stderr.toString()).toBe(0); + expect(JSON.parse(preempt.stdout.toString())).toEqual({ slot, reason: "red-main-fix", preempted: true, forced: false }); + expect(await holder.child.exited).toBe(PREEMPTED_EXIT); + expect(await holder.output).toContain("neither passed nor failed"); + expect(readFileSync(join(dir, "cleanup"), "utf8")).toBe("cleaned\n"); + expect(await fix.child.exited).toBe(0); + expect(await fix.output).toContain("FIX_AFTER_CLEANUP"); + const kinds = readHistory(ledger).filter(event => event.slot === slot).map(event => event.kind); + expect(kinds).toEqual(["queued", "admitted", "preempt-requested", "preempted"]); + const admittedFix = readHistory(ledger).find(event => event.kind === "admitted" && event.priority === "red-main-fix")!; + expect(Date.parse(admittedFix.at as string)).toBeGreaterThanOrEqual(statSync(join(dir, "cleanup")).mtimeMs - 5); + }); + + test("preempt refuses a slot held under a different orchestrator, and any reason but a red-main fix", async () => { + const { dir, ledger, timings } = fixture(); + const holder = admit(join(dir, "ithaca"), ledger, timings, `while [ ! -e ${dir}/release ]; do sleep 0.02; done`, + { BRAIN_ORCHESTRATOR_ID: "circe" }); + await until(() => holding(ledger).length === 1, "the holder"); + const slot = holding(ledger)[0]!.id; + const fix = admit(join(dir, "ogygia"), ledger, timings, "true", { BRAIN_RED_MAIN_FIX: "7", BRAIN_ORCHESTRATOR_ID: "odysseus" }); + await until(() => queued(ledger).length === 1, "the fix waiter"); + const attempt = (orchestrator: string, reason: string) => Bun.spawnSync([process.execPath, SCRIPT, "preempt", slot, "--reason", reason], + { env: env(ledger, { BRAIN_ORCHESTRATOR_ID: orchestrator }), stdout: "pipe", stderr: "pipe" }); + const foreign = attempt("odysseus", "red-main-fix"); + expect(foreign.exitCode).toBe(2); + expect(foreign.stderr.toString()).toContain("outside the caller's orchestrator subtree"); + const unruled = attempt("circe", "faster-feedback"); + expect(unruled.exitCode).toBe(2); + expect(unruled.stderr.toString()).toContain("only permitted to admit a red-main fix"); + expect(holding(ledger)[0]?.preempt).toBeUndefined(); + expect(readHistory(ledger).some(event => event.kind === "preempt-requested")).toBe(false); + Bun.write(join(dir, "release"), ""); + expect(await Promise.all([holder.child.exited, fix.child.exited])).toEqual([0, 0]); + }); + + test("a descendant whose environment lost the slot marker still inherits its ancestor's slot", async () => { + const { dir, ledger, timings } = fixture(); + // The nested heavy command's caller replaced its environment (as test + // fixtures and sandbox wrappers do), dropping BRAIN_HOST_ADMISSION. + const nested = `env -u BRAIN_HOST_ADMISSION ${process.execPath} -e 'const m = await import("${SCRIPT}"); ` + + `const code = await m.ensureHostAdmission("nested"); console.log(code === undefined ? "NESTED_INHERITED" : "NESTED_QUEUED"); process.exit(code ?? 0)'`; + const holder = admit(join(dir, "ithaca"), ledger, timings, nested); + expect(await Promise.race([holder.child.exited, Bun.sleep(8_000).then(() => "deadlocked")])).toBe(0); + expect(await holder.output).toContain("NESTED_INHERITED"); + }); + + test("a descendant without a ledger directory finds its test process's private ledger", () => { + const own = testLedgerFor(process.pid, processIdentity(process.pid)!.start); + expect(existsSync(own), "the test preload creates this process's private ledger").toBe(true); + const child = Bun.spawnSync([process.execPath, "-e", `console.log((await import(${JSON.stringify(SCRIPT)})).ledgerDir({}))`], + { env: { PATH: process.env.PATH! }, stdout: "pipe", stderr: "pipe" }); + expect(child.stdout.toString().trim(), child.stderr.toString()).toBe(own); + }); + + test("the admitted command receives the workspace lease descriptor, not only its marker", async () => { + // This test runs under the real workspace lease; a command in a nested + // user namespace can prove that inheritance only through the descriptor. + const { dir, ledger, timings } = fixture(); + // Node, unlike Bun, gets no offline-harness child preload, which would + // itself forward the lease and hide a wrapper that dropped it. + const node = Bun.which("node"); + if (!node) throw new Error("Lease forwarding proof requires node, as the browser wrapper does"); + const child = Bun.spawn([node, SCRIPT, "run", "--poll-ms", "20", "--timings-out", timings, "--", "sh", "-c", + 'echo "LEASE=$BRAIN_WORKSPACE_LEASE"; for f in /proc/$$/fd/*; do echo "FD $(basename $f) $(readlink $f)"; done'], + { cwd: dir, env: { ...process.env, ...env(ledger) }, stdout: "pipe", stderr: "pipe" }); + children.push(child); + const [out, err] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text()]); + expect(await child.exited, err).toBe(0); + const lease = JSON.parse(out.match(/^LEASE=(.*)$/m)![1]!); + const lock = realpathSync(join(ROOT, "tmp/workspace-operation/output.lock")); + expect(out, "LEASE_DESCRIPTOR_REACHES_THE_ADMITTED_COMMAND").toContain(`FD ${lease.fd} ${lock}`); + }); + + test("the limit defaults from the CPU count and is overridden by BRAIN_HOST_ADMISSION_LIMIT", () => { + expect(admissionLimit({}, 16)).toBe(4); + expect(admissionLimit({}, 2)).toBe(1); + expect(admissionLimit({ BRAIN_HOST_ADMISSION_LIMIT: "3" }, 16)).toBe(3); + expect(() => admissionLimit({ BRAIN_HOST_ADMISSION_LIMIT: "0" }, 16)).toThrow("positive integer"); + }); +}); + +describe("which test runs are heavy", () => { + const costs = { "tests/raft.test.ts": HEAVY_TEST_FILE_SECONDS, "tests/oar.test.ts": 1 }; + test("the integrated suite, runtime-host, native and long files need admission; a focused file does not", () => { + expect(heavyTestReason(ROOT, ROOT, [], costs)).toBe("integrated suite"); + expect(heavyTestReason(ROOT, ROOT, ["--timeout", "30000"], costs)).toBe("integrated suite"); + expect(heavyTestReason(ROOT, ROOT, ["packages/ui-react/tests/draft-runtime.test.ts"], costs)).toBe("runtime-host tests"); + expect(heavyTestReason(ROOT, ROOT, ["scripts/native-proof/reference-pool.native.ts"], costs)).toBe("native tests"); + expect(heavyTestReason(ROOT, ROOT, ["./tests/raft.test.ts"], costs)).toBe("long test file tests/raft.test.ts"); + expect(heavyTestReason(ROOT, ROOT, ["./tests"], costs)).toBe("long test file tests/raft.test.ts"); + expect(heavyTestReason(ROOT, ROOT, ["./tests/oar.test.ts"], costs)).toBeUndefined(); + }); +}); diff --git a/tests/local-checks.test.ts b/tests/local-checks.test.ts index 321dda97d1..5e98b1435d 100644 --- a/tests/local-checks.test.ts +++ b/tests/local-checks.test.ts @@ -117,6 +117,7 @@ test("focused and full local CLI refuse setup before downstream proof while plan for (const helper of ["ci-plan", "ci-runner", "check-packages"]) { writeFileSync(join(dir, `scripts/${helper}.ts`), `export * from ${JSON.stringify(join(owner, `scripts/${helper}.ts`))};\n`); } + writeFileSync(join(dir, "scripts/host-admission.mjs"), `export * from ${JSON.stringify(join(owner, "scripts/host-admission.mjs"))};\n`); writeFileSync(join(dir, "package.json"), JSON.stringify({ private: true, workspaces: ["packages/*"] })); writeFileSync(join(dir, "packages/ithaca/package.json"), JSON.stringify({ name: "@odysseus/ithaca" })); writeFileSync(join(dir, ".gitignore"), "tmp/\n"); @@ -347,7 +348,7 @@ function importFixture() { const dir = fixture(); const root = join(import.meta.dir, ".."); mkdirSync(join(dir, "scripts")); - for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { + for (const helper of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(root, "scripts", helper), join(dir, "scripts", helper)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/test-script.test.ts b/tests/test-script.test.ts index fe5a182067..c8749b7fa8 100644 --- a/tests/test-script.test.ts +++ b/tests/test-script.test.ts @@ -33,7 +33,7 @@ async function run(args: string[], env: Record = {}) { if (existsSync(script)) { mkdirSync(join(dir, "scripts")); cpSync(script, join(dir, "scripts/test.ts")); - for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { + for (const helper of ["runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", helper), join(dir, "scripts", helper)); } // The actual preload also owns cleanup for the shared CLI harness. @@ -118,6 +118,30 @@ describe("root test script, run for real", () => { expect(await ran(["--test-name-pattern", "--balanced-shard=1/3", "other"])).toEqual(["other"]); }); + test("the integrated suite waits for a host admission slot; a focused path does not (#2943)", async () => { + const ledger = mkdtempSync(join(tmpdir(), "odysseus-test-admission-")); + try { + // The caller's own slot, if any, must not admit these runs. + const env = { BRAIN_HOST_ADMISSION_DIR: ledger, BRAIN_HOST_ADMISSION_LIMIT: "1", BRAIN_HOST_ADMISSION: "" }; + const holder = Bun.spawn([process.execPath, join(ROOT, "scripts/host-admission.mjs"), "run", "--poll-ms", "20", "--", "sh", "-c", `while [ ! -e ${ledger}/release ]; do sleep 0.02; done`], + { env: { ...process.env, ...env }, stdout: "ignore", stderr: "ignore" }); + while (!(existsSync(join(ledger, "state.json")) && readFileSync(join(ledger, "state.json"), "utf8").includes('"holding"'))) await Bun.sleep(10); + const focused = await run(["other"], env); + expect(focused.ran).toEqual(["other"]); + expect(focused.output).not.toContain("Waiting for a host admission slot"); + const pending = run([], env); + while (!readFileSync(join(ledger, "state.json"), "utf8").includes('"queued"')) await Bun.sleep(10); + writeFileSync(join(ledger, "release"), ""); + const integrated = await pending; + expect(integrated.code).toBe(0); + expect(integrated.ran).toEqual(DEFAULT_SET); + expect(integrated.output).toContain("Waiting for a host admission slot (1 on this host): position 1 of 1"); + expect(await holder.exited).toBe(0); + } finally { + rmSync(ledger, { recursive: true, force: true }); + } + }); + test("a failing test fails the command", async () => { const result = await run(["other"], { FAIL_OTHER: "1" }); expect(result.ran).toEqual(["other"]); diff --git a/tests/test-shards.test.ts b/tests/test-shards.test.ts index 02ab31ca6d..fd415d32bd 100644 --- a/tests/test-shards.test.ts +++ b/tests/test-shards.test.ts @@ -59,7 +59,7 @@ describe("balanced shards run the root command for real", () => { mkdirSync(join(dir, "scripts")); const manifest = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8")); writeFileSync(join(dir, "package.json"), JSON.stringify({ name: "fixture", scripts: { test: manifest.scripts.test } })); - for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs"]) { + for (const script of ["test.ts", "runtime-test-builds.ts", "test-invocation.ts", "test-invocation-child.ts", "publishable-packages.ts", "test-shards.ts", "test-shard-costs.json", "test-network-preload.ts", "test-network-guard.ts", "test-network-child-preload.ts", "workspace-lease.mjs", "host-admission.mjs"]) { cpSync(join(ROOT, "scripts", script), join(dir, "scripts", script)); } mkdirSync(join(dir, "packages/core/tests"), { recursive: true }); diff --git a/tests/visual-runner.test.ts b/tests/visual-runner.test.ts index bf71256395..9eb3c01672 100644 --- a/tests/visual-runner.test.ts +++ b/tests/visual-runner.test.ts @@ -27,6 +27,8 @@ async function invoke(args: string[], exit = 0, imageState: "warm"|"cold"|"drift await mkdir(dirname(resolve(root, file)), { recursive: true }); await copyFile(resolve(import.meta.dir, "..", file), resolve(root, file)); } + // The host side of the wrapper admits itself through the host ledger (#2943). + await copyFile(resolve(import.meta.dir, "../scripts/host-admission.mjs"), resolve(root, "scripts/host-admission.mjs")); for (const domain of diagramSourceDomains) { const manifest = JSON.parse(await readFile(resolve(root, `packages/${domain}/package.json`), "utf8")); const alias = resolve(root, "node_modules", manifest.name);await mkdir(dirname(alias), {recursive:true});await symlink(resolve(root, "packages", domain), alias); diff --git a/tests/workspace-lease.test.ts b/tests/workspace-lease.test.ts index 0c84faeb64..bccaaa810b 100644 --- a/tests/workspace-lease.test.ts +++ b/tests/workspace-lease.test.ts @@ -251,7 +251,7 @@ const spawn = (...args) => { test("the real pinned container wrapper waits for host ownership of its mounted checkout", async () => { const root = fixture(helper, false, false, join(project, "tmp", "workspace-lease-container")); for (const path of ["scripts", "packages/ui-kit", "node_modules/vitest"]) mkdirSync(join(root, path), { recursive: true }); - for (const name of ["visual.mjs", "workspace-lease.mjs", "prepare-diagram-export-source.mjs", "diagram-export-source.mjs", "diagram-export-installation.mjs", "diagram-export-producer.mjs"]) copyFileSync(join(project, "scripts", name), join(root, "scripts", name)); + for (const name of ["visual.mjs", "workspace-lease.mjs", "host-admission.mjs", "prepare-diagram-export-source.mjs", "diagram-export-source.mjs", "diagram-export-installation.mjs", "diagram-export-producer.mjs"]) copyFileSync(join(project, "scripts", name), join(root, "scripts", name)); writeFileSync(join(root, "node_modules/vitest/vitest.mjs"), 'import {writeFileSync} from "node:fs";writeFileSync(new URL("../../vitest-entered",import.meta.url),"native container acquired ownership\\n");\n'); const owner = start(root, "write", "hold", "host"); await entered(root, "host");