#!/usr/bin/env bun // Enforce, as a ratchet, that a child process this tree waits on carries a deadline: a `timeout` // (or an abort `signal`) in its options. An untimed child that hangs hangs its parent with it, and // a synchronous wait cannot even be interrupted by a test's own timeout — the gate sat on one. // Bun's shell (`Bun.$`, or `$` imported from `'bun'`) spawns a child too and takes no deadline, so // every shell call in shipped source is a site — a pin with its sentence, or a `Bun.spawn` instead. // bun run spawn-timeout [--json] [--explain] · bun run scripts/spawn-timeout.ts --unpin import { renderFixShellArg } from '@ultimat3/core'; import { maskLiterals } from '../packages/core/src/source-mask'; import { balancedClose } from './lib/balanced-paren'; import { corpus } from './lib/corpus'; import type { Finding } from './lib/log'; import type { PinTarget } from './lib/pin-edit'; import { pinRaiseFix, pinRaiseOf } from './lib/pin-edit'; import { ratchetPinMain } from './lib/pin-edit-main'; import type { PinTable, RatchetGap } from './lib/ratchet'; import { ratchetGaps } from './lib/ratchet'; import type { SiteProbe } from './lib/ratchet-sites'; import { leadSite, newSitesFirst, siteList, siteTarget } from './lib/ratchet-sites'; import { isTestPath, lineOf } from './lib/source-scan'; import { SPAWN_TIMEOUT_PINS, SPAWN_TIMEOUT_PINS_FILE } from './lib/spawn-timeout-pins'; import { hasTopLevelKey } from './lib/top-level-key'; const SCRIPT = 'spawn-timeout'; /** Where this ratchet's pins live: what its over finding's raise and `--write-pin` edit. */ export const SPAWN_TIMEOUT_PIN_TARGET: PinTarget = { script: 'scripts/spawn-timeout.ts', file: SPAWN_TIMEOUT_PINS_FILE, table: 'SPAWN_TIMEOUT_PINS', }; const EXPLAIN = 'bun run scripts/spawn-timeout.ts --explain --json lists every one'; /** The calls that block until the child exits. Bare names cover a `node:child_process` import. */ const SYNC_CALL = /(? hasTopLevelKey(args, DEADLINE); /** Every local name the file's imports from `'bun'` give the shell: `$`, or its alias. */ const shellNames = (masked: string, source: string): readonly string[] => { const names: string[] = []; for (const match of source.matchAll(BUN_IMPORT)) { if (masked[match.index] !== 'i') continue; for (const part of (match[1] ?? '').split(',')) { const spec = /^\$(?:\s+as\s+([A-Za-z_$][\w$]*))?$/.exec(part.trim()); if (spec !== null) names.push(spec[1] ?? '$'); } } return names; }; export interface SpawnSite { readonly path: string; readonly line: number; /** The call as written, up to its `(` — `Bun.spawnSync`, `Bun.spawn`. */ readonly call: string; } /** * Every untimed spawn in one file. TWO SHAPES, TWO SCOPES: a synchronous spawn blocks the event * loop until the child exits, so it is read everywhere, tests included. `Bun.spawn` is read in * shipped source only — a test's `Bun.spawn` + awaited `exited` is the house shape, bounded by the * test timeout — and a long-lived child its caller kills (a dev server, an editor, a forwarded CLI) * is a pin with its sentence, never a silent pass. * * WHAT IT CANNOT SEE: options passed as a variable (`Bun.spawn(cmd, options)`) read as untimed, and * a `timeout` that is `undefined` at run time reads as timed — and so does a `signal` that is no * `AbortSignal` bounding the child, since only the property NAME is read. A floor, not a proof. */ export function scanSpawns( path: string, source: string, masked: string = maskLiterals(source), ): readonly SpawnSite[] { const shipped = !isTestPath(path); const sites: SpawnSite[] = []; const read = (pattern: RegExp): void => { for (const match of masked.matchAll(pattern)) { const open = match.index + match[0].length - 1; const close = balancedClose(masked, open); const args = masked.slice(open + 1, close < 0 ? masked.length : close); if (hasDeadline(args)) continue; sites.push({ path, line: lineOf(masked, match.index), call: match[0].replace(/\s*\($/, '') }); } }; read(SYNC_CALL); if (shipped) { read(ASYNC_CALL); const shell = (pattern: RegExp, call: string): void => { for (const match of masked.matchAll(pattern)) { sites.push({ path, line: lineOf(masked, match.index), call }); } }; shell(BUN_SHELL, 'Bun.$'); for (const name of shellNames(masked, source)) { shell(new RegExp(`(? a.line - b.line); } export type SpawnGap = RatchetGap; export const checkSpawns = ( sites: readonly SpawnSite[], pins: PinTable, scanned: boolean, ): readonly SpawnGap[] => ratchetGaps(sites, pins, scanned); const at = (site: SpawnSite | undefined): string => site === undefined ? '' : `${site.path}:${String(site.line)}`; const overFinding = (gap: SpawnGap): Finding => ({ code: 'X_SPAWN_UNTIMED', cause: `${gap.pkg} spawns ${String(gap.found)} child process(es) with no timeout and is pinned at ${String(gap.pinned)} — ${siteList(gap, (site) => `${at(site)} (${site.call})`, EXPLAIN)} — and a child that hangs hangs whatever waits on it, the gate included`, fix: `{ timeout: 60_000 } // a deadline in milliseconds, in the options of the call at ${siteTarget(gap, at)}; for a child its caller kills itself, ${pinRaiseFix(pinRaiseOf(SPAWN_TIMEOUT_PIN_TARGET, gap))}, the reason naming who ends it`, at: at(leadSite(gap)), }); const staleFinding = (gap: SpawnGap): Finding => ({ code: 'X_SPAWN_TIMEOUT_PIN_STALE', cause: `${gap.pkg} is pinned at ${String(gap.pinned)} untimed spawn(s) and has ${String(gap.found)}, so the pin would let ${String(gap.pinned - gap.found)} back in`, fix: `bun run scripts/spawn-timeout.ts --unpin ${renderFixShellArg(gap.pkg, '')}`, at: SPAWN_TIMEOUT_PINS_FILE, }); const unexplainedFinding = (gap: SpawnGap): Finding => ({ code: 'X_SPAWN_TIMEOUT_PIN_UNEXPLAINED', cause: `${gap.pkg} is pinned with a blank reason, so nothing says who ends its ${String(gap.found)} untimed child process(es)`, fix: `grep -n ${renderFixShellArg(gap.pkg, '')} ${SPAWN_TIMEOUT_PINS_FILE} # write in that row what ends each untimed child in ${gap.pkg} — or add timeout: to each and run bun run scripts/spawn-timeout.ts --unpin ${gap.pkg}`, at: SPAWN_TIMEOUT_PINS_FILE, }); /** `corpus` already throws below its floor; this is the ratchet's own empty-input answer. */ const unscannedFinding = (): Finding => ({ code: 'X_CORPUS_UNSCANNED', cause: 'no source file was read, so every package reports zero untimed spawns and the ratchet enforces nothing', fix: "grep -n 'CORPUS_PATTERNS' scripts/lib/corpus.ts # edit it so it matches this repo layout, then: bun run scripts/spawn-timeout.ts", at: 'scripts/lib/corpus.ts', }); export const spawnFindingFor = (gap: SpawnGap): Finding => { switch (gap.kind) { case 'over': return overFinding(gap); case 'stale': return staleFinding(gap); case 'unexplained': return unexplainedFinding(gap); case 'unscanned': return unscannedFinding(); } }; /** * Every site in the tree, read off the shared corpus and its CACHED mask. Masking is nearly the * whole cost of a scan (1.3 s of 1.3 s over 6,849 files, measured 2026-10-18), and `spawnGaps` * reads the tree a second time: masked here, it paid that cost twice per call. */ export const spawnSites = async (root: string): Promise => (await corpus(root, 'source')).flatMap((file) => scanSpawns(file.path, file.source, file.masked)); const PROBE: SiteProbe = { rescan: scanSpawns, line: (site) => site.line }; export const spawnGaps = async (root: string): Promise => newSitesFirst(root, checkSpawns(await spawnSites(root), SPAWN_TIMEOUT_PINS, true), PROBE); if (import.meta.main) { await ratchetPinMain({ target: SPAWN_TIMEOUT_PIN_TARGET, script: SCRIPT, pinsFile: SPAWN_TIMEOUT_PINS_FILE, pins: SPAWN_TIMEOUT_PINS, sites: spawnSites, findingFor: spawnFindingFor, probe: PROBE, clean: 'every child process this tree waits on carries a timeout, or sits under its package pin', }); }