Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: verify pregate group exit after transient signal refusal (#13458)

Adam Eivy6f93565eb1dc
diff --git a/scripts/pregate.js b/scripts/pregate.js
index b56aa858af..53225b5672 100644
--- a/scripts/pregate.js
+++ b/scripts/pregate.js
@@ -559,25 +559,55 @@ async function cancelStage(stage, child, closed, signal) {
return IS_WIN32 ? { settled: true } : sweepStageGroup(child.pid);
}
+/** Bounded diagnostic only: ps is never evidence that an owned group is absent. */
+function describeStageGroup(pgid) {
+ const result = spawnSync('ps', ['-A', '-o', 'pid=,pgid=,stat='], {
+ encoding: 'utf8', timeout: 1000, maxBuffer: 1024 * 1024,
+ });
+ if (result.error || result.status !== 0) return `unavailable (${result.error?.code ?? result.status ?? result.signal ?? 'unknown'})`;
+ const members = result.stdout.split('\n').map(line => line.trim().split(/\s+/))
+ .filter(([, group]) => Number(group) === pgid);
+ // No command lines, arguments, identities, or unrelated processes in evidence.
+ return members.slice(0, 16).map(([pid, , state]) => `${pid}:${state}`).join(',')
+ + (members.length > 16 ? ',…' : '') || 'none observed';
+}
+
/**
- * Kill whatever is still in a stage's process group once its leader exited:
- * a descendant that ignored a signal or outlived its launcher keeps running
- * (and writing to inherited descriptors) into the next stage or past pregate.
- * ESRCH is the proof the group is empty. POSIX only. Resolves
- * `{ settled, lingered?, reason? }`.
+ * Kill whatever outlived a stage leader. Only ESRCH for the exact owned group
+ * proves settlement. Darwin can return EPERM for an existing zombie-only
+ * group (XNU killpg1 filters SZOMB); wait for reaping with read-only probes,
+ * within the original deadline, rather than mistaking refusal for permission
+ * trouble or treating zombies/ps output as proof of absence.
*/
-async function sweepStageGroup(pgid) {
- const deadline = Date.now() + STAGE_SETTLE_MS;
+export async function sweepStageGroup(pgid, {
+ kill = process.kill, now = Date.now, wait = delay, inspect = describeStageGroup,
+} = {}) {
+ const deadline = now() + STAGE_SETTLE_MS;
for (let attempt = 0; ; attempt += 1) {
try {
- process.kill(-pgid, 'SIGKILL');
+ kill(-pgid, 'SIGKILL');
} catch (error) {
- return error.code === 'ESRCH'
- ? { settled: true, lingered: attempt > 0 }
- : { settled: false, reason: `group kill failed (${error.code ?? 'unknown'})` };
+ if (error.code === 'ESRCH') return { settled: true, lingered: attempt > 0 };
+ const refusal = `group kill failed (${error.code ?? 'unknown'})`;
+ if (error.code !== 'EPERM') return { settled: false, reason: `${refusal}; pgid=${pgid}; members=${inspect(pgid)}` };
+ let members;
+ for (;;) {
+ let probe = 'present';
+ try {
+ kill(-pgid, 0);
+ } catch (probeError) {
+ if (probeError.code === 'ESRCH') return { settled: true, lingered: attempt > 0 };
+ probe = probeError.code ?? 'unknown';
+ }
+ members ??= inspect(pgid);
+ if (!['present', 'EPERM'].includes(probe) || now() >= deadline) {
+ return { settled: false, reason: `${refusal}; pgid=${pgid}; probe=${probe}; members=${members}` };
+ }
+ await wait(Math.min(25, Math.max(0, deadline - now())));
+ }
}
- if (Date.now() >= deadline) return { settled: false, reason: 'group members remained after SIGKILL' };
- await delay(25);
+ if (now() >= deadline) return { settled: false, reason: 'group members remained after SIGKILL' };
+ await wait(25);
}
}
diff --git a/scripts/pregate.test.js b/scripts/pregate.test.js
index 38b2643f0b..58d076b576 100644
--- a/scripts/pregate.test.js
+++ b/scripts/pregate.test.js
@@ -25,6 +25,7 @@ import {
parseArgs,
pregateWorkerEnv,
stageSpawnEnv,
+ sweepStageGroup,
suiteSelected,
uncoveredSuites,
UNCOVERED_SUITES,
@@ -61,6 +62,55 @@ const DEFAULT_OPTIONS = {
skipDb: false, skipBrowser: false, skipBuild: false, skipSmoke: false,
};
+describe('owned stage group settlement', () => {
+ const pgid = 424242;
+ const fail = code => { throw Object.assign(new Error(code), { code }); };
+
+ it('waits through a zombie-only EPERM until a fresh exact-group probe returns ESRCH', async () => {
+ let elapsed = 0;
+ const calls = [];
+ const result = await sweepStageGroup(pgid, {
+ kill: (pid, signal) => {
+ calls.push([pid, signal]);
+ // Reproduce the held-zombie -> reaped transition without timing sleeps.
+ return fail(elapsed === 0 ? 'EPERM' : 'ESRCH');
+ },
+ now: () => elapsed,
+ wait: async ms => { elapsed += ms; },
+ inspect: group => { expect(group).toBe(pgid); return `${pgid}:Z`; },
+ });
+ expect(result.settled).toBe(true);
+ expect(calls).toEqual([[-pgid, 'SIGKILL'], [-pgid, 0], [-pgid, 0]]);
+ expect(elapsed).toBe(25);
+ });
+
+ it.each([
+ ['live', 'present', '424242:S'],
+ ['uninspectable', 'EPERM', 'unavailable (EACCES)'],
+ ['zombie-only', 'EPERM', '424242:Z'],
+ ['empty snapshot with denied probe', 'EPERM', 'none observed'],
+ ['failed probe', 'EIO', 'unavailable (EIO)'],
+ ])('refuses a %s group without a fresh ESRCH', async (_state, probe, members) => {
+ let elapsed = 0;
+ const signals = [];
+ const result = await sweepStageGroup(pgid, {
+ kill: (pid, signal) => {
+ expect(pid).toBe(-pgid);
+ signals.push(signal);
+ if (signal === 'SIGKILL') return fail('EPERM');
+ if (probe !== 'present') return fail(probe);
+ },
+ now: () => elapsed,
+ wait: async ms => { elapsed += ms; },
+ inspect: group => { expect(group).toBe(pgid); return members; },
+ });
+ expect(result).toEqual({ settled: false, reason: `group kill failed (EPERM); pgid=${pgid}; probe=${probe}; members=${members}` });
+ expect(signals[0]).toBe('SIGKILL');
+ expect(signals.slice(1).every(signal => signal === 0)).toBe(true);
+ expect(elapsed).toBe(probe === 'EIO' ? 0 : 5000);
+ });
+});
+
describe('resolvePlanStages', () => {
it('runs only the scopes the plan selected', () => {
const stages = resolvePlanStages(planWith());
@@ -691,6 +741,36 @@ describe('pregate hidden-content invocation', () => {
}
});
+ // #13458: replay the kernel's exit/signal crossing at the CLI boundary.
+ // Only an actually absent group gets the injected refusal; the subsequent
+ // probe must still go to the kernel, and the receipt must remain truthful.
+ it.skipIf(process.platform === 'win32')('verifies exact group absence after an exit-crossing EPERM', () => {
+ const preload = join(scratch, 'exit-crossing.cjs');
+ writeFileSync(preload, `
+ const kill = process.kill.bind(process);
+ process.kill = (pid, signal) => {
+ if (pid < 0 && signal === 'SIGKILL') {
+ try { kill(pid, 0); } catch (error) {
+ if (error.code !== 'ESRCH') throw error;
+ console.log('fixture-exit-crossing pgid=' + -pid);
+ throw Object.assign(new Error('exit crossing'), { code: 'EPERM' });
+ }
+ }
+ return kill(pid, signal);
+ };
+ `);
+ write(trackedPath, `${clean}updated\n`);
+ const result = spawnSync(process.execPath, ['--require', preload, 'scripts/pregate.js', '--base', base, '--skip-lint'], {
+ cwd: root, encoding: 'utf8',
+ });
+ expect(result.stdout).toMatch(/fixture-exit-crossing pgid=\d+/);
+ expect(result.status, result.stderr).toBe(0);
+ expect(result.stdout).toContain('Pregate passed');
+ const report = JSON.parse(readFileSync(join(root, PREGATE_REPORT_PATH), 'utf8'));
+ expect(report.passed).toBe(true);
+ expect(report.stages[0]).toMatchObject({ name: 'hidden-content scan', status: 'passed' });
+ });
+
// run-ci-tests.js leaves npm and Vitest in pregate's stage group, so pregate
// owns them on every exit path, not only on cancellation.
it.skipIf(process.platform === 'win32')('kills a descendant still running in the stage group after the stage exits', () => {