@hominis/fireforge 0.47.0 → 0.47.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/bin/fireforge.js +6 -0
  3. package/dist/build-info.json +4 -4
  4. package/dist/src/commands/test-harness-teardown.d.ts +62 -0
  5. package/dist/src/commands/test-harness-teardown.js +128 -0
  6. package/dist/src/commands/test-register.js +2 -1
  7. package/dist/src/commands/test-run.d.ts +2 -0
  8. package/dist/src/commands/test-run.js +36 -7
  9. package/dist/src/commands/test-verdict.d.ts +19 -4
  10. package/dist/src/commands/test-verdict.js +22 -4
  11. package/dist/src/commands/test.js +18 -10
  12. package/dist/src/core/config-paths.d.ts +1 -1
  13. package/dist/src/core/config-paths.js +1 -0
  14. package/dist/src/core/config-validate-test-toolchains.js +7 -0
  15. package/dist/src/core/file-lock.js +16 -9
  16. package/dist/src/core/harness-helper-pids.d.ts +98 -0
  17. package/dist/src/core/harness-helper-pids.js +240 -0
  18. package/dist/src/core/harness-orphans.d.ts +53 -8
  19. package/dist/src/core/harness-orphans.js +125 -44
  20. package/dist/src/core/mach.d.ts +16 -0
  21. package/dist/src/core/mach.js +6 -1
  22. package/dist/src/core/marionette-preflight.js +9 -3
  23. package/dist/src/core/parent-exit-watchdog.d.ts +62 -0
  24. package/dist/src/core/parent-exit-watchdog.js +69 -0
  25. package/dist/src/types/commands/options.d.ts +11 -1
  26. package/dist/src/types/config.d.ts +7 -0
  27. package/dist/src/utils/process-group.d.ts +5 -1
  28. package/dist/src/utils/process-group.js +7 -3
  29. package/dist/src/utils/process.d.ts +18 -0
  30. package/dist/src/utils/process.js +14 -2
  31. package/docs/configuration.md +7 -1
  32. package/docs/lifecycle-invariants.md +17 -1
  33. package/docs/machine-output.md +22 -9
  34. package/docs/testing.md +68 -4
  35. package/package.json +1 -1
@@ -22,10 +22,15 @@
22
22
  * for the same reason. FireForge has no business reporting, let alone
23
23
  * terminating, a process it cannot attribute to the harness.
24
24
  *
25
- * `--reap-orphans` opts into termination. Without it the census is
26
- * report-only, exactly like the `Orphaned harness workers` doctor check
27
- * (which covers a different shape: reparented Python multiprocessing
28
- * workers, matched on PPID 1 and accumulated CPU time).
25
+ * `--reap-orphans` (or `test.reapOrphans: "reap"` in `fireforge.json`) opts
26
+ * into termination. Without it the census is report-only, exactly like the
27
+ * `Orphaned harness workers` doctor check (which covers a different shape:
28
+ * reparented Python multiprocessing workers, matched on PPID 1 and
29
+ * accumulated CPU time).
30
+ *
31
+ * The anchoring and termination primitives are exported for the teardown
32
+ * reaper in `harness-helper-pids.ts`, which applies the same objdir rule to
33
+ * the helpers THIS run launched, after mach has exited.
29
34
  */
30
35
  import { toError } from '../utils/errors.js';
31
36
  import { info, verbose, warn } from '../utils/logger.js';
@@ -33,42 +38,91 @@ import { exec } from '../utils/process.js';
33
38
  import { parsePsDuration } from '../utils/ps-duration.js';
34
39
  import { sleep } from '../utils/sleep.js';
35
40
  /**
36
- * Harness helper executables/scripts. Every one of these is started by the
37
- * mochitest/xpcshell harness and is expected to die with it. None of them
38
- * is a thing a developer runs by hand.
41
+ * Harness helper binaries, matched on the executable's basename. Every one
42
+ * of these is started by the mochitest/xpcshell harness and is expected to
43
+ * die with it. None of them is a thing a developer runs by hand.
44
+ */
45
+ const HELPER_BINARY = /^(?:xpcshell|ssltunnel|http3server|moz-http2)(?:\.exe)?$/;
46
+ /** Interpreters the harness runs its helper scripts under. */
47
+ const HELPER_INTERPRETER = /^(?:python[\d.]*|Python|node)(?:\.exe)?$/;
48
+ /** Harness helper scripts, matched on the interpreter's script argument. */
49
+ const HELPER_SCRIPT = /(?:^|[/\\])(?:pywebsocket\w*\.py|websocket_server\.py|websocketprocessbridge\.py|moz-http2\.js|http2_server\.js|httpd\.js|server\.js|runtests\.py|runxpcshelltests\.py)$/;
50
+ function basename(token) {
51
+ const cut = Math.max(token.lastIndexOf('/'), token.lastIndexOf('\\'));
52
+ return cut === -1 ? token : token.slice(cut + 1);
53
+ }
54
+ /**
55
+ * True when `command` IS a harness helper: its executable is a helper
56
+ * binary, or an interpreter whose first argument is a helper script.
57
+ *
58
+ * Structural on purpose. An earlier version matched the helper names
59
+ * anywhere in the command line, which is right for the httpd (`xpcshell -g
60
+ * … -f …/server.js`) and wrong for everything that merely mentions such a
61
+ * path: an editor opened on `server.js`, a shell whose command text quotes
62
+ * it, a `grep` over the objdir. Report-only, that printed a misleading
63
+ * `kill`; under the reap posture it terminated the operator's shell.
39
64
  */
40
- const HARNESS_HELPER_PATTERN = /\b(?:xpcshell|pywebsocket\w*|websocket_server\.py|ssltunnel|moz-http2|http2_server|httpd\.js|server\.js|runtests\.py|runxpcshelltests\.py)\b/;
65
+ export function matchesHarnessHelper(command) {
66
+ const [exe, first] = command.trim().split(/\s+/);
67
+ if (exe === undefined)
68
+ return false;
69
+ if (HELPER_BINARY.test(basename(exe)))
70
+ return true;
71
+ if (first === undefined || !HELPER_INTERPRETER.test(basename(exe)))
72
+ return false;
73
+ return HELPER_SCRIPT.test(first);
74
+ }
41
75
  /** Objdir provenance: an explicit objdir path, a `obj-…` path segment, or `_tests/`. */
42
- function isObjdirAnchored(command, objDir) {
76
+ export function isObjdirAnchored(command, objDir) {
43
77
  if (objDir !== undefined && objDir.length > 0 && command.includes(objDir))
44
78
  return true;
45
79
  if (/[/\\]obj-[^/\\\s]*[/\\]/.test(command))
46
80
  return true;
47
81
  return /[/\\]_tests[/\\]/.test(command);
48
82
  }
83
+ /** Pids of `selfPid` and every ancestor of it, as far as the listing reaches. */
84
+ function ancestorsOf(rows, selfPid) {
85
+ const parentOf = new Map(rows.map((r) => [r.pid, r.ppid]));
86
+ const chain = new Set();
87
+ let cursor = selfPid;
88
+ while (cursor !== undefined && cursor > 0 && !chain.has(cursor)) {
89
+ chain.add(cursor);
90
+ cursor = parentOf.get(cursor);
91
+ }
92
+ return chain;
93
+ }
49
94
  /**
50
95
  * Scans `ps -axo pid=,ppid=,etime=,command=` output for surviving harness
51
96
  * helpers. Pure, so it is fixture-testable without spawning anything.
52
97
  *
98
+ * FireForge's own process, its direct children and its ancestors are never
99
+ * candidates: the terminal shell FireForge runs under can carry the helper
100
+ * paths in its own command text, and must never be offered for a kill.
101
+ *
53
102
  * @param psOutput - Raw `ps` output
54
103
  * @param objDir - Absolute objdir of this project, when known. Widens the
55
104
  * provenance test beyond the generic `obj-…` path segment
56
- * @param selfPid - This process's pid, excluded so FireForge cannot report
57
- * itself
105
+ * @param selfPid - This process's pid
58
106
  */
59
107
  export function findOrphanedHarnessProcesses(psOutput, objDir, selfPid = process.pid) {
60
- const found = [];
108
+ const rows = [];
61
109
  for (const line of psOutput.split('\n')) {
62
110
  const match = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.+)$/.exec(line);
63
111
  if (!match)
64
112
  continue;
65
- const pid = Number(match[1]);
66
- const ppid = Number(match[2]);
67
- const elapsed = match[3] ?? '';
68
- const command = (match[4] ?? '').trim();
69
- if (pid === selfPid || ppid === selfPid)
113
+ rows.push({
114
+ pid: Number(match[1]),
115
+ ppid: Number(match[2]),
116
+ elapsed: match[3] ?? '',
117
+ command: (match[4] ?? '').trim(),
118
+ });
119
+ }
120
+ const excluded = ancestorsOf(rows, selfPid);
121
+ const found = [];
122
+ for (const { pid, ppid, elapsed, command } of rows) {
123
+ if (excluded.has(pid) || ppid === selfPid)
70
124
  continue;
71
- if (!HARNESS_HELPER_PATTERN.test(command))
125
+ if (!matchesHarnessHelper(command))
72
126
  continue;
73
127
  if (!isObjdirAnchored(command, objDir))
74
128
  continue;
@@ -85,6 +139,8 @@ export function findOrphanedHarnessProcesses(psOutput, objDir, selfPid = process
85
139
  }
86
140
  /** Grace period between SIGTERM and SIGKILL when reaping. */
87
141
  const REAP_GRACE_MS = 500;
142
+ /** Wait after SIGKILL before the final liveness probe, so the parent can collect the exit. */
143
+ const KILL_SETTLE_MS = 200;
88
144
  /** Longest command excerpt carried into the report line. */
89
145
  const COMMAND_EXCERPT_LIMIT = 160;
90
146
  /**
@@ -102,7 +158,8 @@ export function formatOrphanReport(orphans) {
102
158
  `it):\n${rows}\n` +
103
159
  `Survivors like these slow every later run without appearing anywhere in its output — a ` +
104
160
  `three-second suite taking minutes of wall clock is the usual symptom. Terminate them with ` +
105
- `"kill ${pids}", or re-run with --reap-orphans to have FireForge do it.`);
161
+ `"kill ${pids}", re-run with --reap-orphans, or set test.reapOrphans to "reap" in ` +
162
+ `fireforge.json to have FireForge do it at every preflight.`);
106
163
  }
107
164
  /** Thin exec wrapper for the process listing (tests mock `exec` instead). */
108
165
  async function listSystemProcesses() {
@@ -125,63 +182,87 @@ async function listSystemProcesses() {
125
182
  * @param objDir - Absolute objdir of this project, when known
126
183
  * @param options - `reap` terminates each recognized survivor (SIGTERM,
127
184
  * then SIGKILL for anything that stays)
128
- * @returns The census, empty when nothing was found or nothing could be probed
185
+ * @returns The census (empty when nothing was found or nothing could be
186
+ * probed) and how many of them are confirmed gone after reaping (0 in
187
+ * report-only mode)
129
188
  */
130
189
  export async function reportOrphanedHarnessProcesses(objDir, options = {}) {
131
190
  if (process.platform === 'win32')
132
- return [];
191
+ return { orphans: [], reaped: 0 };
133
192
  let psOutput;
134
193
  try {
135
194
  psOutput = await listSystemProcesses();
136
195
  }
137
196
  catch (error) {
138
197
  verbose(`Orphan preflight: could not scan processes (${toError(error).message}); skipping.`);
139
- return [];
198
+ return { orphans: [], reaped: 0 };
140
199
  }
141
200
  const orphans = findOrphanedHarnessProcesses(psOutput, objDir);
142
201
  if (orphans.length === 0) {
143
202
  verbose('Orphan preflight: no surviving harness helper processes.');
144
- return [];
203
+ return { orphans: [], reaped: 0 };
145
204
  }
146
205
  warn(formatOrphanReport(orphans));
147
- if (options.reap === true) {
148
- await reapOrphanedHarnessProcesses(orphans);
206
+ const reaped = options.reap === true ? await terminateHarnessProcesses(orphans, '--reap-orphans') : 0;
207
+ return { orphans, reaped };
208
+ }
209
+ /** Liveness probe: `kill(pid, 0)` throws for a pid that is gone. */
210
+ export function isPidAlive(pid) {
211
+ try {
212
+ process.kill(pid, 0);
213
+ return true;
214
+ }
215
+ catch {
216
+ return false;
149
217
  }
150
- return orphans;
151
218
  }
152
219
  /**
153
- * Terminates each census entry: SIGTERM first, then SIGKILL for anything
154
- * still alive. Failures are reported, never thrown. A process that exited
155
- * between the census and the signal is the common case rather than an error.
220
+ * Terminates each entry: SIGTERM first, then SIGKILL for anything still
221
+ * alive after the grace period. Failures are reported, never thrown. A
222
+ * process that exited between the listing and the signal is the common case
223
+ * rather than an error.
224
+ *
225
+ * @param targets - Processes to terminate, already attributed to the harness
226
+ * by the caller (objdir anchor rule)
227
+ * @param label - Prefix for the log lines, naming which path is reaping
228
+ * (`--reap-orphans` at preflight, `teardown` after mach exits)
229
+ * @returns How many targets are confirmed gone afterwards
156
230
  */
157
- async function reapOrphanedHarnessProcesses(orphans) {
158
- for (const orphan of orphans) {
231
+ export async function terminateHarnessProcesses(targets, label) {
232
+ let reaped = 0;
233
+ for (const target of targets) {
159
234
  try {
160
- process.kill(orphan.pid, 'SIGTERM');
235
+ process.kill(target.pid, 'SIGTERM');
161
236
  }
162
237
  catch (error) {
163
- verbose(`--reap-orphans: SIGTERM to ${orphan.pid} failed (${toError(error).message}).`);
238
+ verbose(`${label}: SIGTERM to ${target.pid} failed (${toError(error).message}).`);
164
239
  continue;
165
240
  }
166
241
  // Grace period before escalating: the httpd shape in the field
167
242
  // incident ignored SIGTERM while spinning, but an ordinary helper exits
168
243
  // promptly and must not be SIGKILLed for being slow by a millisecond.
169
244
  await sleep(REAP_GRACE_MS);
170
- let alive = true;
171
- try {
172
- process.kill(orphan.pid, 0);
173
- }
174
- catch {
175
- alive = false;
176
- }
177
- if (alive) {
245
+ if (isPidAlive(target.pid)) {
178
246
  try {
179
- process.kill(orphan.pid, 'SIGKILL');
247
+ process.kill(target.pid, 'SIGKILL');
180
248
  }
181
249
  catch (error) {
182
- verbose(`--reap-orphans: SIGKILL to ${orphan.pid} failed (${toError(error).message}).`);
250
+ verbose(`${label}: SIGKILL to ${target.pid} failed (${toError(error).message}).`);
183
251
  }
252
+ // A killed process answers kill(0) until its parent (launchd, for a
253
+ // reparented survivor) has collected it, which takes a moment.
254
+ await sleep(KILL_SETTLE_MS);
255
+ }
256
+ // Counted only when the probe agrees: the verdict line will carry this
257
+ // number, and a SIGKILL that was sent is not the same as a process that
258
+ // is gone.
259
+ if (isPidAlive(target.pid)) {
260
+ warn(`${label}: PID ${target.pid} is still alive after SIGKILL; inspect it by hand.`);
261
+ }
262
+ else {
263
+ reaped += 1;
264
+ info(`${label}: terminated PID ${target.pid}.`);
184
265
  }
185
- info(`--reap-orphans: terminated PID ${orphan.pid}.`);
186
266
  }
267
+ return reaped;
187
268
  }
@@ -37,6 +37,16 @@ export interface MachOptions {
37
37
  * layer's {@link ExecOptions.envUnset}.
38
38
  */
39
39
  envUnset?: readonly string[];
40
+ /**
41
+ * Observes every raw output chunk of a capture dispatch, on either stream,
42
+ * before the echo filter. The test dispatchers feed the harness helper-pid
43
+ * tracker from it. Capture-only, like `annotateKnownTeardownNoise`.
44
+ */
45
+ onOutputChunk?: (stream: 'stdout' | 'stderr', chunk: string) => void;
46
+ /** Exec-layer hook, see {@link ProcessGroupOptions.onProcessGroup}. Capture-only. */
47
+ onProcessGroup?: (pgid: number) => void;
48
+ /** Exec-layer hook, see {@link ProcessGroupOptions.postCloseSweep}. Capture-only. */
49
+ postCloseSweep?: () => Promise<void>;
40
50
  }
41
51
  /**
42
52
  * Result of running a mach command while capturing streamed output.
@@ -247,6 +257,12 @@ export interface MachTestSuiteOptions {
247
257
  * markers that quiet it. See {@link CODING_AGENT_ENV_MARKERS}.
248
258
  */
249
259
  fullOutput?: boolean | undefined;
260
+ /**
261
+ * Harness teardown hooks (`fireforge test`): the helper-pid tracker feed,
262
+ * the process-group announcement, and the post-close reap of the helpers
263
+ * the harness launched. See {@link MachOptions}.
264
+ */
265
+ teardown?: Pick<MachOptions, 'onOutputChunk' | 'onProcessGroup' | 'postCloseSweep'> | undefined;
250
266
  }
251
267
  /**
252
268
  * Runs one mach test command (`mach test` / `mach xpcshell-test` / `mach
@@ -96,7 +96,10 @@ export async function runMachCapture(args, engineDir, options = {}) {
96
96
  // storybook) runs as a process-group leader and is group-reaped on
97
97
  // exit/abort. See ExecOptions.processGroup.
98
98
  processGroup: true,
99
+ ...(options.onProcessGroup ? { onProcessGroup: options.onProcessGroup } : {}),
100
+ ...(options.postCloseSweep ? { postCloseSweep: options.postCloseSweep } : {}),
99
101
  onStdout: (data) => {
102
+ options.onOutputChunk?.('stdout', data);
100
103
  stdout += data;
101
104
  if (stdout.length > CAPTURE_TAIL_LIMIT) {
102
105
  stdout = stdout.slice(-CAPTURE_TAIL_LIMIT);
@@ -110,6 +113,7 @@ export async function runMachCapture(args, engineDir, options = {}) {
110
113
  process.stdout.write(stdoutFilter ? stdoutFilter.transform(data) : data);
111
114
  },
112
115
  onStderr: (data) => {
116
+ options.onOutputChunk?.('stderr', data);
113
117
  stderr += data;
114
118
  if (stderr.length > CAPTURE_TAIL_LIMIT) {
115
119
  stderr = stderr.slice(-CAPTURE_TAIL_LIMIT);
@@ -407,12 +411,13 @@ function testVerbosityEnvUnset(fullOutput) {
407
411
  * @param options - Engine checkout, test paths, extra args, env, verbosity
408
412
  */
409
413
  export async function runMachTestSuite(kind, options) {
410
- const { engineDir, testPaths = [], args = [], env, fullOutput } = options;
414
+ const { engineDir, testPaths = [], args = [], env, fullOutput, teardown } = options;
411
415
  const guard = await installMachResourceGuard(engineDir);
412
416
  const envUnset = testVerbosityEnvUnset(fullOutput);
413
417
  return runMachCapture([kind, ...testPaths, ...args], engineDir, {
414
418
  env: { ...guard.env, ...env },
415
419
  ...(envUnset ? { envUnset } : {}),
420
+ ...teardown,
416
421
  annotateKnownTeardownNoise: true,
417
422
  });
418
423
  }
@@ -154,9 +154,13 @@ export async function runMarionettePreflight(engineDir, options = {}) {
154
154
  // (missing dylib, wrong CPU arch, corrupt profile) before the socket
155
155
  // poll swallows the full overall budget waiting for bytes that will
156
156
  // never come.
157
+ // Ref'd (sleep's default), like every wait in this probe: the browser is a
158
+ // detached child, so once it has exited nothing else holds the event
159
+ // loop, and an unref'd wait here let Node exit 0 mid-preflight with no
160
+ // `Marionette preflight:` line and no verdict at all.
157
161
  const settleDeadline = Math.min(spawnSettleMs, Math.max(0, timeoutMs - elapsed()));
158
162
  if (settleDeadline > 0) {
159
- await sleep(settleDeadline, { unref: true });
163
+ await sleep(settleDeadline);
160
164
  }
161
165
  if (hasChildExited(spawnedChild)) {
162
166
  return fail('browser-spawns', `Browser process exited during spawn (exit code ${spawnedChild.exitCode}, signal ${spawnedChild.signalCode ?? 'none'}). ` +
@@ -207,7 +211,9 @@ async function teardownPreflightChild(child, forwarder, closure, profileDir) {
207
211
  killProcessTree(child, 'SIGTERM', process.platform !== 'win32');
208
212
  // Small escalation: if the child doesn't honour SIGTERM quickly, SIGKILL
209
213
  // so we don't leave a ghost mach process around after a failed probe.
210
- await sleep(500, { unref: true });
214
+ // Ref'd: an unref'd wait between a SIGTERM and its escalation lets Node
215
+ // exit mid-grace and skip the escalation.
216
+ await sleep(500);
211
217
  if (!hasChildExited(child)) {
212
218
  killProcessTree(child, 'SIGKILL', process.platform !== 'win32');
213
219
  }
@@ -255,7 +261,7 @@ async function waitForMarionetteSocket(port, connectFn, keepTrying) {
255
261
  if (result.ok) {
256
262
  return { ok: true };
257
263
  }
258
- await sleep(400, { unref: true });
264
+ await sleep(400);
259
265
  }
260
266
  return { ok: false };
261
267
  }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Detects the death of FireForge's own parent while a harness runs.
3
+ *
4
+ * A supervisor that SIGKILLs the process above `fireforge test` (the
5
+ * 2026-09-13 incident: a gate killed its `npm` step at the 15-minute bound)
6
+ * signals nothing below it. FireForge is not told; its stdout pipe merely
7
+ * breaks, and the broken-pipe handler swallows EPIPE on purpose so `| head`
8
+ * works. The mach tree it spawned as a separate process group keeps running
9
+ * under nobody's supervision, and the httpd in that tree spun at 100% CPU
10
+ * for hours.
11
+ *
12
+ * SIGKILL cannot be caught, but reparenting can be observed: once the parent
13
+ * is gone, `process.ppid` changes (to launchd/init, or to a subreaper). This
14
+ * watchdog polls for that while a dispatch is in flight and fires once. It
15
+ * does not decide what to do about it; the test command tears down the
16
+ * harness tree and ends the run.
17
+ *
18
+ * Off on Windows: `process.ppid` is not refreshed there after the parent
19
+ * exits, and there is no process group to signal in response anyway.
20
+ */
21
+ /** Options for {@link startParentExitWatchdog}. */
22
+ export interface ParentExitWatchdogOptions {
23
+ /** Probe interval, default {@link DEFAULT_INTERVAL_MS}. */
24
+ intervalMs?: number;
25
+ /** Called exactly once, the first time the parent is seen to be gone. */
26
+ onParentExit: (info: {
27
+ originalPpid: number;
28
+ currentPpid: number;
29
+ }) => void;
30
+ /**
31
+ * Reads the current parent pid; default `process.ppid`. Injectable because
32
+ * `process.ppid` cannot be stubbed on every Node line: redefining the
33
+ * property is honoured on Node 26 and silently ignored on Node 22, so a
34
+ * test that stubs it passes on one and never observes a reparent on the
35
+ * other.
36
+ */
37
+ readPpid?: () => number;
38
+ }
39
+ /** Handle for a running watchdog. */
40
+ export interface ParentExitWatchdog {
41
+ /** Stops probing. Idempotent. A stopped watchdog never fires. */
42
+ stop(): void;
43
+ }
44
+ /**
45
+ * True once any watchdog in this process has seen the parent die. The
46
+ * dispatch loop reads it to end the run instead of classifying the killed
47
+ * harness as a crash and retrying it under a parent that no longer exists.
48
+ */
49
+ export declare function parentExited(): boolean;
50
+ /**
51
+ * Forgets an observed parent exit.
52
+ *
53
+ * @internal Exported only so tests can reach it. It is not part of the
54
+ * public surface.
55
+ */
56
+ export declare function resetParentExitForTests(): void;
57
+ /**
58
+ * Starts probing `process.ppid`. The timer is unref'd so the watchdog can
59
+ * never be the thing keeping FireForge alive; while a child runs, the child
60
+ * does that.
61
+ */
62
+ export declare function startParentExitWatchdog(options: ParentExitWatchdogOptions): ParentExitWatchdog;
@@ -0,0 +1,69 @@
1
+ // SPDX-License-Identifier: EUPL-1.2
2
+ /**
3
+ * Detects the death of FireForge's own parent while a harness runs.
4
+ *
5
+ * A supervisor that SIGKILLs the process above `fireforge test` (the
6
+ * 2026-09-13 incident: a gate killed its `npm` step at the 15-minute bound)
7
+ * signals nothing below it. FireForge is not told; its stdout pipe merely
8
+ * breaks, and the broken-pipe handler swallows EPIPE on purpose so `| head`
9
+ * works. The mach tree it spawned as a separate process group keeps running
10
+ * under nobody's supervision, and the httpd in that tree spun at 100% CPU
11
+ * for hours.
12
+ *
13
+ * SIGKILL cannot be caught, but reparenting can be observed: once the parent
14
+ * is gone, `process.ppid` changes (to launchd/init, or to a subreaper). This
15
+ * watchdog polls for that while a dispatch is in flight and fires once. It
16
+ * does not decide what to do about it; the test command tears down the
17
+ * harness tree and ends the run.
18
+ *
19
+ * Off on Windows: `process.ppid` is not refreshed there after the parent
20
+ * exits, and there is no process group to signal in response anyway.
21
+ */
22
+ /** How often the parent is probed. Cheap (one syscall), so a short interval is fine. */
23
+ const DEFAULT_INTERVAL_MS = 2000;
24
+ let parentExitObserved = false;
25
+ /**
26
+ * True once any watchdog in this process has seen the parent die. The
27
+ * dispatch loop reads it to end the run instead of classifying the killed
28
+ * harness as a crash and retrying it under a parent that no longer exists.
29
+ */
30
+ export function parentExited() {
31
+ return parentExitObserved;
32
+ }
33
+ /**
34
+ * Forgets an observed parent exit.
35
+ *
36
+ * @internal Exported only so tests can reach it. It is not part of the
37
+ * public surface.
38
+ */
39
+ export function resetParentExitForTests() {
40
+ parentExitObserved = false;
41
+ }
42
+ /**
43
+ * Starts probing `process.ppid`. The timer is unref'd so the watchdog can
44
+ * never be the thing keeping FireForge alive; while a child runs, the child
45
+ * does that.
46
+ */
47
+ export function startParentExitWatchdog(options) {
48
+ if (process.platform === 'win32') {
49
+ return { stop: () => undefined };
50
+ }
51
+ const readPpid = options.readPpid ?? (() => process.ppid);
52
+ const originalPpid = readPpid();
53
+ let timer = setInterval(() => {
54
+ const currentPpid = readPpid();
55
+ if (currentPpid === originalPpid)
56
+ return;
57
+ stop();
58
+ parentExitObserved = true;
59
+ options.onParentExit({ originalPpid, currentPpid });
60
+ }, options.intervalMs ?? DEFAULT_INTERVAL_MS);
61
+ timer.unref();
62
+ function stop() {
63
+ if (timer === undefined)
64
+ return;
65
+ clearInterval(timer);
66
+ timer = undefined;
67
+ }
68
+ return { stop };
69
+ }
@@ -612,9 +612,19 @@ export interface TestOptions extends EngineLockWaitable {
612
612
  * project's objdir. The census itself runs on every test dispatch and is
613
613
  * report-only. This flag opts into the kill. Survivors slow later runs
614
614
  * without appearing in their output, so the visibility is the default and
615
- * the termination is the choice.
615
+ * the termination is the choice. `test.reapOrphans: "reap"` in
616
+ * `fireforge.json` makes it the repo's default.
616
617
  */
617
618
  reapOrphans?: boolean;
619
+ /**
620
+ * Path to write the harness process-group id to, rewritten on every mach
621
+ * spawn (each retry attempt and shard) and removed when the run ends under
622
+ * FireForge's control. mach runs as its own process-group leader, so a
623
+ * supervisor's kill of its own group never reaches it; a supervisor that
624
+ * had to SIGKILL FireForge takes the whole harness tree afterwards with
625
+ * `kill -- -<pgid>`. The file survives exactly that case, by design.
626
+ */
627
+ pgidFile?: string;
618
628
  /** Permit tests against packageable engine edits newer than the last successful build. */
619
629
  allowStaleBuild?: boolean;
620
630
  /**
@@ -47,6 +47,13 @@ export interface TestConfig {
47
47
  canaryPath?: string;
48
48
  /** Short no-output ceiling for `fireforge test --canary`, in seconds. */
49
49
  canaryTimeoutSeconds?: number;
50
+ /**
51
+ * What the preflight orphan census does with a harness helper that
52
+ * survived an earlier run in this objdir: `report` (default) names it and
53
+ * proceeds; `reap` terminates it and stamps `orphans-reaped=<n>` on the
54
+ * verdict line. `--reap-orphans` is the per-invocation equivalent.
55
+ */
56
+ reapOrphans?: 'report' | 'reap';
50
57
  }
51
58
  /** A single external executable required by a project-specific toolchain. */
52
59
  export interface ExternalToolRequirement {
@@ -32,8 +32,12 @@ interface ProcessGroupSurvivor {
32
32
  * about anything that still refuses to die. POSIX only (no-op on win32).
33
33
  * The only kill target is `-pgid`, never anything outside the group.
34
34
  * A healthy run costs exactly one `pgrep`.
35
+ *
36
+ * `context` names why the group is being reaped in the warning; the default
37
+ * is the post-close sweep. The parent-exit watchdog passes its own, because
38
+ * there the group is still running when the sweep begins.
35
39
  */
36
- export declare function sweepProcessGroup(pgid: number, graceMs?: number): Promise<{
40
+ export declare function sweepProcessGroup(pgid: number, graceMs?: number, context?: string): Promise<{
37
41
  survivors: ProcessGroupSurvivor[];
38
42
  }>;
39
43
  export {};
@@ -130,15 +130,19 @@ function describeSurvivors(list) {
130
130
  * about anything that still refuses to die. POSIX only (no-op on win32).
131
131
  * The only kill target is `-pgid`, never anything outside the group.
132
132
  * A healthy run costs exactly one `pgrep`.
133
+ *
134
+ * `context` names why the group is being reaped in the warning; the default
135
+ * is the post-close sweep. The parent-exit watchdog passes its own, because
136
+ * there the group is still running when the sweep begins.
133
137
  */
134
- export async function sweepProcessGroup(pgid, graceMs = SWEEP_GRACE_MS) {
138
+ export async function sweepProcessGroup(pgid, graceMs = SWEEP_GRACE_MS, context = 'after exit') {
135
139
  if (process.platform === 'win32')
136
140
  return { survivors: [] };
137
141
  const survivors = await listGroupSurvivors(pgid);
138
142
  if (survivors.length === 0)
139
143
  return { survivors };
140
- warn(`Harness process group ${pgid} left ${survivors.length} surviving ` +
141
- `process(es) after exit — reaping the group. ${describeSurvivors(survivors)}`);
144
+ warn(`Harness process group ${pgid} has ${survivors.length} live ` +
145
+ `process(es) ${context} — reaping the group. ${describeSurvivors(survivors)}`);
142
146
  try {
143
147
  process.kill(-pgid, 'SIGTERM');
144
148
  }
@@ -85,6 +85,24 @@ export interface ProcessGroupOptions {
85
85
  * whenever this option is set.
86
86
  */
87
87
  processGroup?: boolean;
88
+ /**
89
+ * Receives the process-group id (the detached child's pid) right after a
90
+ * group-leader spawn. Lets a caller expose the group to a supervisor that
91
+ * cannot signal FireForge itself gracefully (`fireforge test --pgid-file`),
92
+ * or hold it for a teardown of its own. Not called when no group was
93
+ * created (`processGroup` unset, or win32).
94
+ */
95
+ onProcessGroup?: (pgid: number) => void;
96
+ /**
97
+ * Extra teardown the caller owns, awaited after the child's `close` and
98
+ * the post-run group sweep, before the child's closure settles. Placed
99
+ * here rather than after the wrapper resolves so the bin signal handler's
100
+ * `waitForActiveChildShutdown` covers it too: a reap that ran after the
101
+ * wrapper resolved would race `process.exit` on a forwarded SIGTERM. Must
102
+ * never throw; a rejection is swallowed so it cannot mask the child's
103
+ * result.
104
+ */
105
+ postCloseSweep?: () => Promise<void>;
88
106
  }
89
107
  /**
90
108
  * Executes a command and returns its output.
@@ -154,6 +154,8 @@ async function spawnTracked(spec) {
154
154
  detached: usesProcessGroup,
155
155
  });
156
156
  const groupPid = usesProcessGroup ? child.pid : undefined;
157
+ if (groupPid !== undefined)
158
+ options.onProcessGroup?.(groupPid);
157
159
  spec.attach?.(child);
158
160
  // Group-aware kills route to the whole tree. A non-group child is killed
159
161
  // directly by the forwarder's own `child.kill`.
@@ -183,11 +185,21 @@ async function spawnTracked(spec) {
183
185
  closure.settle();
184
186
  resolve(spec.result(code, signal));
185
187
  };
188
+ // Group sweep first (it takes the helpers that stayed in the group),
189
+ // then the caller's own sweep (the ones that did not), then settle.
190
+ const callerSweep = () => {
191
+ const sweep = options.postCloseSweep;
192
+ if (sweep === undefined) {
193
+ finish();
194
+ return;
195
+ }
196
+ sweep().then(finish, finish);
197
+ };
186
198
  if (groupPid !== undefined) {
187
- sweepProcessGroup(groupPid).then(finish, finish);
199
+ sweepProcessGroup(groupPid).then(callerSweep, callerSweep);
188
200
  }
189
201
  else {
190
- finish();
202
+ callerSweep();
191
203
  }
192
204
  });
193
205
  });
@@ -113,7 +113,13 @@ gaps does not move a patch out of the band its category owns.
113
113
  ## `test`
114
114
 
115
115
  `test.canaryPath` and `test.canaryTimeoutSeconds` supply the defaults for
116
- `fireforge test --canary`. See [`testing.md`](testing.md).
116
+ `fireforge test --canary`.
117
+
118
+ `test.reapOrphans` is `"report"` (default) or `"reap"`: what the preflight
119
+ census does with a harness helper that survived an earlier run in this
120
+ objdir. `"reap"` terminates it and stamps `orphans-reaped=<n>` on the verdict
121
+ line; `--reap-orphans` does the same for one invocation. The objdir anchor
122
+ rule is the same under both. See [`testing.md`](testing.md).
117
123
 
118
124
  ## `buildAudit`
119
125