Skip to content

Commit 88dd2c1

Browse files
committed
fix(setup): gate prewarm to applied registrations and supervise the runner tree
Address review findings on the prewarm step: - Gate the prewarm on at least one applied client registration (configured_<client>), so an empty plan or a skill-only run never installs into the package-runner cache; the step now only follows registrations the user approved in this transaction. - Replace execFileOutput with a supervised spawn: on timeout the whole runner tree stops through cleanupWindowsProcessTree on Windows and a process-group kill on POSIX, because killing only the direct child leaves npm holding the inherited output pipes past the deadline. - Emit started and completed progress events around the prewarm so an interactive cold install no longer looks like a frozen setup.
1 parent c7b552a commit 88dd2c1

4 files changed

Lines changed: 253 additions & 61 deletions

File tree

‎src/application/Setup.ts‎

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import { setupCleanupError, setupCleanupReason } from "./SetupCleanupOwner.js";
3535
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
3636
import type { SetupSkillInstallError } from "./SetupSkill.js";
3737
import type { SetupHopperInstallFailure } from "./SetupInstallFailure.js";
38+
import type { SetupRegistrationPrewarm } from "./SetupRegistrationPrewarm.js";
3839

3940
/** Discover, approve, and apply setup actions idempotently. */
4041
export const runSetup = async (
@@ -378,14 +379,34 @@ const runSetupWorkflow = async (
378379
return withHopperFailure(await failSkill(skillFailure));
379380
}
380381
}
381-
const prewarm = await host.prewarmRegistrationRunner?.();
382-
if (prewarm?.status === "failed")
382+
// The prewarm only follows client registrations the user approved; an empty
383+
// plan or a skill-only run must not install anything.
384+
const prewarmEligible = appliedActions.some((id) =>
385+
id.startsWith("configured_"),
386+
);
387+
let prewarm: SetupRegistrationPrewarm | undefined;
388+
if (prewarmEligible && host.prewarmRegistrationRunner !== undefined) {
383389
emitProgress(options, {
384390
actionId: "prewarm_registration_runner",
385391
label: "REA package-runner cache",
386-
state: "warning",
387-
detail: prewarm.reason,
392+
state: "started",
393+
detail: "Preparing the pinned package entry",
388394
});
395+
prewarm = await host.prewarmRegistrationRunner();
396+
if (prewarm.status === "failed")
397+
emitProgress(options, {
398+
actionId: "prewarm_registration_runner",
399+
label: "REA package-runner cache",
400+
state: "warning",
401+
detail: prewarm.reason,
402+
});
403+
else if (prewarm.status === "warmed")
404+
emitProgress(options, {
405+
actionId: "prewarm_registration_runner",
406+
label: "REA package-runner cache",
407+
state: "completed",
408+
});
409+
}
389410
const doctor = summarizeDoctor(await host.doctor(readinessScope));
390411
const remediation = combineRemediation(
391412
hopperFailure?.remediation ??

‎src/application/SetupRegistrationPrewarm.test.ts‎

Lines changed: 77 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,26 @@ import { describe, expect, it } from "vitest";
22

33
import { PRODUCT_IDENTITY } from "../identity.js";
44
import {
5+
launchRegistrationRunnerCommand,
56
materializeRegistrationRunnerCache,
67
registrationPrewarmCommand,
7-
type RegistrationRunnerSpawn,
8+
type RegistrationRunnerLaunch,
9+
type RegistrationRunnerLauncher,
810
} from "./SetupRegistrationPrewarm.js";
911

1012
const specifier = PRODUCT_IDENTITY.registrationPackageSpecifier;
1113

14+
const launch = (
15+
overrides: Partial<RegistrationRunnerLaunch> = {},
16+
): RegistrationRunnerLaunch => ({
17+
exitCode: 0,
18+
signal: null,
19+
stdout: "",
20+
stderr: "",
21+
timedOut: false,
22+
...overrides,
23+
});
24+
1225
describe("registrationPrewarmCommand", () => {
1326
it("replaces the server subcommand of an npx registration", () => {
1427
expect(registrationPrewarmCommand(["npx", "-y", specifier, "mcp"])).toEqual(
@@ -48,52 +61,48 @@ describe("registrationPrewarmCommand", () => {
4861
});
4962

5063
describe("materializeRegistrationRunnerCache", () => {
51-
it("skips direct launchers without spawning", async () => {
52-
let spawned = 0;
53-
const spawn: RegistrationRunnerSpawn = async () => {
54-
spawned += 1;
64+
it("skips direct launchers without launching", async () => {
65+
let launched = 0;
66+
const launcher: RegistrationRunnerLauncher = async () => {
67+
launched += 1;
68+
return launch();
5569
};
5670
const result = await materializeRegistrationRunnerCache(
5771
["/opt/rea/rea", "mcp"],
5872
{},
59-
spawn,
73+
launcher,
6074
);
6175
expect(result).toEqual({ status: "skipped", reason: "direct_launcher" });
62-
expect(spawned).toBe(0);
76+
expect(launched).toBe(0);
6377
});
6478

6579
it("materializes the pinned spec once and reports warmed", async () => {
66-
const launches: (readonly string[])[] = [];
67-
const spawn: RegistrationRunnerSpawn = async (
80+
const commands: (readonly string[])[] = [];
81+
const launcher: RegistrationRunnerLauncher = async (
6882
command,
6983
arguments_,
7084
options,
7185
) => {
72-
launches.push([command, ...arguments_]);
73-
expect(options.timeout).toBeGreaterThan(0);
86+
commands.push([command, ...arguments_]);
87+
expect(options.timeoutMs).toBeGreaterThan(0);
7488
expect(options.env.REA_PREWARM_PROBE).toBe("1");
7589
expect(options.cwd.length).toBeGreaterThan(0);
90+
return launch({ stdout: "6.7.0\n" });
7691
};
7792
const result = await materializeRegistrationRunnerCache(
7893
["npx", "-y", specifier, "mcp"],
7994
{ REA_PREWARM_PROBE: "1" },
80-
spawn,
95+
launcher,
8196
);
8297
expect(result).toEqual({ status: "warmed" });
83-
expect(launches).toEqual([["npx", "-y", specifier, "--version"]]);
98+
expect(commands).toEqual([["npx", "-y", specifier, "--version"]]);
8499
});
85100

86-
it("reports a bounded failure reason with command output facts", async () => {
87-
const failure = Object.assign(
88-
new Error("Command failed: npx -y rea-agents@0.0.0 --version"),
89-
{ stdout: "", stderr: "spawn EPERM\n", code: 1 },
90-
);
101+
it("reports a bounded failure reason for a non-zero exit", async () => {
91102
const result = await materializeRegistrationRunnerCache(
92103
["npx", "-y", specifier, "mcp"],
93104
{},
94-
async () => {
95-
throw failure;
96-
},
105+
async () => launch({ exitCode: 1, stderr: "spawn EPERM\n" }),
97106
);
98107
expect(result.status).toBe("failed");
99108
if (result.status !== "failed") return;
@@ -107,12 +116,55 @@ describe("materializeRegistrationRunnerCache", () => {
107116
const result = await materializeRegistrationRunnerCache(
108117
["npx", "-y", specifier, "mcp"],
109118
{},
110-
async () => {
111-
throw new Error("Command timed out after 180000 ms: npx");
112-
},
119+
async () => launch({ exitCode: null, timedOut: true }),
120+
);
121+
expect(result.status).toBe("failed");
122+
if (result.status !== "failed") return;
123+
expect(result.reason).toContain("timed out");
124+
});
125+
126+
it("reports a spawn failure", async () => {
127+
const result = await materializeRegistrationRunnerCache(
128+
["npx", "-y", specifier, "mcp"],
129+
{},
130+
async () => launch({ exitCode: null, spawnError: "spawn npx ENOENT" }),
113131
);
114132
expect(result.status).toBe("failed");
115133
if (result.status !== "failed") return;
116-
expect(result.reason).toContain("timed out after 180000 ms");
134+
expect(result.reason).toContain("spawn npx ENOENT");
135+
});
136+
});
137+
138+
describe("launchRegistrationRunnerCommand", () => {
139+
it("captures a successful command exit", async () => {
140+
const result = await launchRegistrationRunnerCommand(
141+
process.execPath,
142+
["--version"],
143+
{
144+
env: process.env,
145+
cwd: process.cwd(),
146+
timeoutMs: 30_000,
147+
platform: process.platform,
148+
},
149+
);
150+
expect(result.exitCode).toBe(0);
151+
expect(result.timedOut).toBe(false);
152+
expect(result.stdout.trim().length).toBeGreaterThan(0);
153+
});
154+
155+
it("stops the runner tree at the deadline and reports the timeout", async () => {
156+
const startedAt = Date.now();
157+
const result = await launchRegistrationRunnerCommand(
158+
process.execPath,
159+
["-e", "setInterval(() => {}, 1000)"],
160+
{
161+
env: process.env,
162+
cwd: process.cwd(),
163+
timeoutMs: 300,
164+
platform: process.platform,
165+
},
166+
);
167+
expect(result.timedOut).toBe(true);
168+
expect(Date.now() - startedAt).toBeLessThan(10_000);
117169
});
118170
});

‎src/application/SetupRegistrationPrewarm.ts‎

Lines changed: 109 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
1+
import { spawn, type ChildProcess } from "node:child_process";
12
import { tmpdir } from "node:os";
23

3-
import {
4-
execFileOutput,
5-
execFileOutputFailure,
6-
} from "../process/ExecFileOutput.js";
4+
import { cleanupWindowsProcessTree } from "../process/ProcessOwnership.js";
75
import { inspectClientRegistrationCommand } from "./ClientRegistrationIdentity.js";
86

97
/**
@@ -18,23 +16,32 @@ export type SetupRegistrationPrewarm =
1816

1917
/** One cold package install at setup time; client startup deadlines stay untouched. */
2018
const PREWARM_TIMEOUT_MS = 180_000;
21-
const PREWARM_MAX_OUTPUT_BYTES = 64 * 1024;
19+
const PREWARM_CAPTURE_LIMIT = 64 * 1024;
2220
const PREWARM_REASON_LIMIT = 300;
2321

24-
/** Spawn shape shared with execFileOutput so tests can observe the launch. */
25-
export type RegistrationRunnerSpawn = (
22+
/** Facts of one supervised package-runner launch. */
23+
export interface RegistrationRunnerLaunch {
24+
readonly exitCode: string | number | null;
25+
readonly signal: string | null;
26+
readonly stdout: string;
27+
readonly stderr: string;
28+
readonly timedOut: boolean;
29+
readonly spawnError?: string;
30+
}
31+
32+
/** Launch shape shared with the supervised spawn so tests can observe it. */
33+
export type RegistrationRunnerLauncher = (
2634
command: string,
2735
arguments_: readonly string[],
2836
options: {
29-
readonly timeout: number;
30-
readonly stopSignal: NodeJS.Signals;
31-
readonly maxBuffer: number;
3237
readonly env: Readonly<NodeJS.ProcessEnv>;
3338
/** Neutral directory; inside a REA source checkout the package runner
3439
* would resolve the local project instead of the published entry. */
3540
readonly cwd: string;
41+
readonly timeoutMs: number;
42+
readonly platform: NodeJS.Platform;
3643
},
37-
) => Promise<unknown>;
44+
) => Promise<RegistrationRunnerLaunch>;
3845

3946
/**
4047
* Resolve the cache-materializing variant of a registration command. The
@@ -58,35 +65,105 @@ export const registrationPrewarmCommand = (
5865
export const materializeRegistrationRunnerCache = async (
5966
command: readonly string[],
6067
environment: Readonly<NodeJS.ProcessEnv>,
61-
spawnCommand: RegistrationRunnerSpawn = execFileOutput,
68+
launchCommand: RegistrationRunnerLauncher = launchRegistrationRunnerCommand,
6269
): Promise<SetupRegistrationPrewarm> => {
6370
const prewarm = registrationPrewarmCommand(command);
6471
if (prewarm === undefined)
6572
return { status: "skipped", reason: "direct_launcher" };
66-
try {
67-
await spawnCommand(prewarm[0] ?? "", prewarm.slice(1), {
68-
timeout: PREWARM_TIMEOUT_MS,
69-
stopSignal: "SIGTERM",
70-
maxBuffer: PREWARM_MAX_OUTPUT_BYTES,
71-
env: environment,
72-
cwd: tmpdir(),
73+
const launch = await launchCommand(prewarm[0] ?? "", prewarm.slice(1), {
74+
env: environment,
75+
cwd: tmpdir(),
76+
timeoutMs: PREWARM_TIMEOUT_MS,
77+
platform: process.platform,
78+
});
79+
return launch.timedOut ||
80+
launch.spawnError !== undefined ||
81+
launch.exitCode !== 0
82+
? { status: "failed", reason: prewarmFailureReason(launch) }
83+
: { status: "warmed" };
84+
};
85+
86+
/**
87+
* Stop the whole runner tree: killing only the direct child leaves npm, which
88+
* inherited the output pipes, holding them open past the deadline.
89+
*/
90+
const stopRunnerTree = (
91+
child: ChildProcess,
92+
platform: NodeJS.Platform,
93+
): Promise<void> => {
94+
const pid = child.pid;
95+
if (pid === undefined) return Promise.resolve();
96+
if (platform === "win32")
97+
return cleanupWindowsProcessTree(pid).then(() => undefined);
98+
return new Promise((resolve) => {
99+
try {
100+
process.kill(-pid, "SIGKILL");
101+
} catch {
102+
// The process group may already be gone.
103+
}
104+
resolve();
105+
});
106+
};
107+
108+
export const launchRegistrationRunnerCommand: RegistrationRunnerLauncher = (
109+
command,
110+
arguments_,
111+
options,
112+
) =>
113+
new Promise((resolve) => {
114+
const child = spawn(command, [...arguments_], {
115+
env: options.env,
116+
cwd: options.cwd,
117+
stdio: ["ignore", "pipe", "pipe"],
118+
// POSIX runs the runner in its own group so one signal stops the tree.
119+
...(options.platform === "win32" ? {} : { detached: true }),
120+
});
121+
const stdout = boundedStream(child.stdout);
122+
const stderr = boundedStream(child.stderr);
123+
let timedOut = false;
124+
let spawnError: string | undefined;
125+
const timer = setTimeout(() => {
126+
timedOut = true;
127+
void stopRunnerTree(child, options.platform).finally(() => {
128+
child.kill("SIGKILL");
129+
});
130+
}, options.timeoutMs);
131+
child.on("error", (error: NodeJS.ErrnoException) => {
132+
spawnError = error.message;
73133
});
74-
return { status: "warmed" };
75-
} catch (cause: unknown) {
76-
return { status: "failed", reason: prewarmFailureReason(cause) };
77-
}
134+
child.on("close", (code, signal) => {
135+
clearTimeout(timer);
136+
resolve({
137+
exitCode: code ?? signal,
138+
signal: signal ?? null,
139+
stdout: stdout(),
140+
stderr: stderr(),
141+
timedOut,
142+
...(spawnError === undefined ? {} : { spawnError }),
143+
});
144+
});
145+
});
146+
147+
const boundedStream = (
148+
stream: NodeJS.ReadableStream | null,
149+
): (() => string) => {
150+
let captured = "";
151+
stream?.on("data", (chunk: Buffer) => {
152+
if (captured.length < PREWARM_CAPTURE_LIMIT)
153+
captured += chunk.toString("utf8").slice(0, PREWARM_CAPTURE_LIMIT);
154+
});
155+
return () => captured;
78156
};
79157

80-
const prewarmFailureReason = (cause: unknown): string => {
81-
const failure = execFileOutputFailure(cause);
158+
const prewarmFailureReason = (launch: RegistrationRunnerLaunch): string => {
82159
const observed =
83-
failure === undefined
84-
? cause instanceof Error
85-
? cause.message
86-
: String(cause)
87-
: `exit ${failure.code === null ? "unknown" : String(failure.code)}${
88-
failure.stderr.trim() === "" ? "" : `: ${failure.stderr.trim()}`
89-
}`;
160+
launch.spawnError !== undefined
161+
? launch.spawnError
162+
: launch.timedOut
163+
? `the package runner timed out after the bounded prewarm window`
164+
: `exit ${launch.exitCode === null ? "unknown" : String(launch.exitCode)}${
165+
launch.stderr.trim() === "" ? "" : `: ${launch.stderr.trim()}`
166+
}`;
90167
const normalized = observed
91168
.replace(/\u001b(?:\[[0-9;?]*[ -/]*[@-~]|\([0-9A-Za-z]|[@-Z\\^_])/gu, "")
92169
.replace(/[\u0000-\u001f\u007f]+/gu, " ")

0 commit comments

Comments
 (0)