mirror of
https://github.com/morluto/rea.git
synced 2026-11-22 22:45:47 +00:00
fix(verification): distinguish MCP probe refusals from local deadlines (#13246)
This commit is contained in:
1 parent
75a75a1bd1
commit
eacbd2522a
4 files changed
+128
-150
No files matched your search
@@ -1,7 +1,4 @@
|
||||
import type {
|
||||
McpPhaseBudget,
|
||||
McpStartupBudgets,
|
||||
} from "../../src/config/mcpStartupBudgets.js";
|
||||
import type { McpStartupBudgets } from "../../src/config/mcpStartupBudgets.js";
|
||||
|
||||
interface McpProcessOptions {
|
||||
readonly command: string;
|
||||
@@ -45,9 +42,6 @@ export function profileMcpModuleLoading(
|
||||
/** Parse Linux procfs VmRSS text into bytes. */
|
||||
export function parseLinuxVmRssBytes(status: string): number | null;
|
||||
|
||||
/** Name one MCP startup phase budget. Mirrors `mcpPhaseBudgetRecovery`. */
|
||||
export function mcpStartupPhaseBudgetRecovery(budget: McpPhaseBudget): string;
|
||||
|
||||
/** Collect unique file-backed ESM module URLs from Node diagnostics. */
|
||||
export function createEsmModuleProfileCollector(packageName?: string): {
|
||||
append(chunk: string): void;
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { performance } from "node:perf_hooks";
|
||||
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { Client, SdkError, SdkErrorCode } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import { mcpPhaseBudgetRecovery } from "../../dist/config/mcpStartupBudgets.js";
|
||||
|
||||
const RSS_SAMPLE_INTERVAL_MS = 10;
|
||||
const MAXIMUM_PROFILE_BUFFER_BYTES = 2 * 1_024 * 1_024;
|
||||
@@ -219,29 +220,16 @@ const createLinuxRssSampler = (pid) => {
|
||||
};
|
||||
};
|
||||
|
||||
/** Same sentence as `mcpPhaseBudgetRecovery`; this script cannot import that TypeScript module. */
|
||||
export const mcpStartupPhaseBudgetRecovery = (budget) =>
|
||||
[
|
||||
`The effective ${budget.setting} value for the ${budget.phase} is ${String(budget.milliseconds)} ms (source ${budget.source}; default ${String(budget.defaultMilliseconds)} ms, floor ${String(budget.floorMilliseconds)} ms, maximum ${String(budget.maximumMilliseconds)} ms).`,
|
||||
`Set ${budget.setting} in the environment that starts REA to a positive decimal integer from ${String(budget.floorMilliseconds)} to ${String(budget.maximumMilliseconds)}, then restart REA.`,
|
||||
].join(" ");
|
||||
|
||||
const phaseTimeout = (cause) => {
|
||||
const message = cause instanceof Error ? cause.message : String(cause);
|
||||
return (
|
||||
message.includes("Request timed out") ||
|
||||
message.includes("Maximum total timeout exceeded") ||
|
||||
message.includes("timed out")
|
||||
);
|
||||
};
|
||||
|
||||
const withPhaseBudget = async (budget, operation) => {
|
||||
try {
|
||||
return await operation();
|
||||
} catch (cause) {
|
||||
if (!phaseTimeout(cause)) throw cause;
|
||||
const detail = cause instanceof Error ? cause.message : String(cause);
|
||||
throw new Error(`${detail} ${mcpStartupPhaseBudgetRecovery(budget)}`, {
|
||||
if (
|
||||
!(cause instanceof SdkError) ||
|
||||
cause.code !== SdkErrorCode.RequestTimeout
|
||||
)
|
||||
throw cause;
|
||||
throw new Error(`${cause.message} ${mcpPhaseBudgetRecovery(budget)}`, {
|
||||
cause,
|
||||
});
|
||||
}
|
||||
@@ -249,7 +237,7 @@ const withPhaseBudget = async (budget, operation) => {
|
||||
|
||||
const firstCatalogBudgetExceeded = (budget) =>
|
||||
new Error(
|
||||
`packaged MCP exceeded the first-catalog phase budget. ${mcpStartupPhaseBudgetRecovery(budget)}`,
|
||||
`packaged MCP exceeded the first-catalog phase budget. ${mcpPhaseBudgetRecovery(budget)}`,
|
||||
);
|
||||
|
||||
/**
|
||||
@@ -311,11 +299,11 @@ const assertStartupBudgets = (measurement, policy) => {
|
||||
policy.initialize.milliseconds
|
||||
)
|
||||
throw new Error(
|
||||
`packaged MCP exceeded the initialize phase budget. ${mcpStartupPhaseBudgetRecovery(policy.initialize)}`,
|
||||
`packaged MCP exceeded the initialize phase budget. ${mcpPhaseBudgetRecovery(policy.initialize)}`,
|
||||
);
|
||||
if (measurement.initialized_to_tools_list_ms > policy.toolsList.milliseconds)
|
||||
throw new Error(
|
||||
`packaged MCP exceeded the tools/list phase budget. ${mcpStartupPhaseBudgetRecovery(policy.toolsList)}`,
|
||||
`packaged MCP exceeded the tools/list phase budget. ${mcpPhaseBudgetRecovery(policy.toolsList)}`,
|
||||
);
|
||||
if (
|
||||
measurement.process_started_to_tools_list_ms >
|
||||
|
||||
@@ -1,33 +1,30 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { readFile, watch } from "node:fs/promises";
|
||||
import { performance } from "node:perf_hooks";
|
||||
import { join, resolve } from "node:path";
|
||||
|
||||
import { settledCause } from "../../support/lifecycleHarness.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { testWaitDeadline } from "../../support/testWait.js";
|
||||
import { MAX_NODE_TIMER_DELAY_MS } from "../../../src/domain/analysisResourceLimits.js";
|
||||
|
||||
import {
|
||||
createEsmModuleProfileCollector,
|
||||
mcpStartupPhaseBudgetRecovery,
|
||||
measureMcpStartup,
|
||||
parseLinuxVmRssBytes,
|
||||
profileMcpModuleLoading,
|
||||
} from "../../../scripts/lib/mcp-startup-probe.mjs";
|
||||
import {
|
||||
mcpPhaseBudgetRecovery,
|
||||
resolveMcpStartupBudgets,
|
||||
type McpPhaseBudget,
|
||||
} from "../../../src/config/mcpStartupBudgets.js";
|
||||
import {
|
||||
mcpDoctorDeadlineRecovery,
|
||||
MCP_STARTUP_POLICY,
|
||||
} from "../../../src/config/mcpStartupPolicy.js";
|
||||
import { mcpDoctorDeadlineRecovery } from "../../../src/config/mcpStartupPolicy.js";
|
||||
|
||||
const errorMessage = (cause: unknown): string =>
|
||||
cause instanceof Error ? cause.message : String(cause);
|
||||
|
||||
const expectPhaseText = (text: string, budget: McpPhaseBudget) => {
|
||||
expect(text).toContain(mcpPhaseBudgetRecovery(budget));
|
||||
expect(text).toContain(budget.setting);
|
||||
expect(text).toContain(budget.phase);
|
||||
expect(text).toContain(`${String(budget.milliseconds)} ms`);
|
||||
@@ -35,52 +32,31 @@ const expectPhaseText = (text: string, budget: McpPhaseBudget) => {
|
||||
expect(text).toContain(`default ${String(budget.defaultMilliseconds)} ms`);
|
||||
expect(text).toContain(`floor ${String(budget.floorMilliseconds)} ms`);
|
||||
expect(text).toContain(`maximum ${String(budget.maximumMilliseconds)} ms`);
|
||||
expect(text).toContain("then restart REA");
|
||||
};
|
||||
|
||||
const expectThrownBudget = async (
|
||||
pending: Promise<unknown>,
|
||||
budget: McpPhaseBudget,
|
||||
): Promise<string> => {
|
||||
let caught: unknown;
|
||||
try {
|
||||
await pending;
|
||||
} catch (cause) {
|
||||
caught = cause;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(Error);
|
||||
const message = errorMessage(caught);
|
||||
const failure = await settledCause(pending);
|
||||
expect(failure).toBeInstanceOf(Error);
|
||||
const message = errorMessage(failure);
|
||||
expectPhaseText(message, budget);
|
||||
return message;
|
||||
};
|
||||
|
||||
describe("MCP startup policy", () => {
|
||||
it("names phase budget settings without turning Codex's 30s into a REA knob", () => {
|
||||
const budgets = resolveMcpStartupBudgets({});
|
||||
expect(MCP_STARTUP_POLICY.codexStartupTimeoutSeconds).toBe(30);
|
||||
const initialize = mcpPhaseBudgetRecovery(budgets.initialize);
|
||||
expectPhaseText(initialize, budgets.initialize);
|
||||
expectPhaseText(
|
||||
mcpStartupPhaseBudgetRecovery(budgets.initialize),
|
||||
budgets.initialize,
|
||||
it("distinguishes the doctor budget from Codex client guidance", () => {
|
||||
const budget = resolveMcpStartupBudgets({}).doctor;
|
||||
const doctor = mcpDoctorDeadlineRecovery(budget);
|
||||
expectPhaseText(doctor, budget);
|
||||
expect(doctor).toContain(
|
||||
"Codex startup_timeout_sec of 30 seconds is client guidance",
|
||||
);
|
||||
expectPhaseText(
|
||||
mcpStartupPhaseBudgetRecovery(budgets.toolsList),
|
||||
budgets.toolsList,
|
||||
expect(doctor).toContain(
|
||||
"REA does not enforce that figure as this deadline",
|
||||
);
|
||||
expectPhaseText(
|
||||
mcpStartupPhaseBudgetRecovery(budgets.firstCatalog),
|
||||
budgets.firstCatalog,
|
||||
);
|
||||
const doctor = mcpDoctorDeadlineRecovery(budgets.doctor);
|
||||
expectPhaseText(doctor, budgets.doctor);
|
||||
expect(doctor).toMatch(/Codex.*startup_timeout_sec.*client guidance/iu);
|
||||
expect(doctor).toMatch(/REA does not enforce/iu);
|
||||
const selected = resolveMcpStartupBudgets({
|
||||
REA_MCP_INITIALIZE_BUDGET_MS: "16000",
|
||||
});
|
||||
expect(selected.initialize.milliseconds).toBe(16_000);
|
||||
expect(selected.initialize.source).toBe("setting");
|
||||
expect(selected.toolsList).toEqual(budgets.toolsList);
|
||||
});
|
||||
|
||||
it("parses Linux resident memory without accepting other fields", () => {
|
||||
@@ -93,8 +69,8 @@ describe("MCP startup policy", () => {
|
||||
it("profiles unique file-backed ESM modules without retaining paths", () => {
|
||||
const collector = createEsmModuleProfileCollector();
|
||||
collector.append(
|
||||
"ESM 1: Storing file:///opt/rea/dist/main.js\n" +
|
||||
"ESM 1: Translating StandardModule file:///opt/rea/dist/main.js\n" +
|
||||
"ESM 1: Storing file:///opt/node_modules/rea-agents/dist/main.js\n" +
|
||||
"ESM 1: Translating StandardModule file:///opt/node_modules/rea-agents/dist/main.js\n" +
|
||||
"ESM 1: Storing file:///opt/rea/node_modules/zod/index.js",
|
||||
);
|
||||
|
||||
@@ -102,7 +78,7 @@ describe("MCP startup policy", () => {
|
||||
supported: true,
|
||||
method: "node-debug-esm",
|
||||
unique_file_modules: 2,
|
||||
unique_package_modules: 0,
|
||||
unique_package_modules: 1,
|
||||
unique_dependency_modules: 1,
|
||||
debug_lines: 3,
|
||||
truncated: false,
|
||||
@@ -167,20 +143,6 @@ describe("packaged MCP startup probe failures", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("names the first-catalog budget when startup exceeds it", async () => {
|
||||
const budgetMs = 1;
|
||||
const policy = probePolicy({ firstCatalogBudgetMs: budgetMs });
|
||||
await expectThrownBudget(
|
||||
measureMcpStartup({
|
||||
command: process.execPath,
|
||||
args: [probeChild],
|
||||
environment: { ...process.env, REA_MCP_PROBE_MODE: "serve" },
|
||||
policy,
|
||||
}),
|
||||
policy.firstCatalog,
|
||||
);
|
||||
});
|
||||
|
||||
it("does not add timeout guidance to an unrelated startup failure", async () => {
|
||||
try {
|
||||
await measureMcpStartup({
|
||||
@@ -232,22 +194,22 @@ describe("packaged MCP startup probe failures", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("does not add timeout guidance to an unrelated module-profile failure", async () => {
|
||||
try {
|
||||
await profileMcpModuleLoading({
|
||||
it("keeps a remote tools/list refusal separate from a module-profile deadline", async () => {
|
||||
const message = "upstream catalog cache timed out before this connection";
|
||||
const policy = probePolicy();
|
||||
await expect(
|
||||
profileMcpModuleLoading({
|
||||
command: process.execPath,
|
||||
args: [probeChild],
|
||||
environment: { ...process.env, REA_MCP_PROBE_MODE: "fail" },
|
||||
policy: probePolicy(),
|
||||
environment: {
|
||||
...process.env,
|
||||
REA_MCP_PROBE_MODE: "refuse-list",
|
||||
REA_MCP_PROBE_ERROR_MESSAGE: message,
|
||||
},
|
||||
policy,
|
||||
packageName: "rea-agents",
|
||||
});
|
||||
throw new Error("expected the unrelated probe failure");
|
||||
} catch (cause) {
|
||||
const message = errorMessage(cause);
|
||||
expect(message).not.toContain("expected the unrelated probe failure");
|
||||
for (const budget of Object.values(probePolicy()))
|
||||
expect(message).not.toContain(budget.setting);
|
||||
}
|
||||
}),
|
||||
).rejects.toMatchObject({ code: -32601, message });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -255,56 +217,85 @@ describe("packaged MCP startup probe failures", () => {
|
||||
// than any test deadline, so only the first-catalog budget can end the wait
|
||||
// before the test's deadline does.
|
||||
describe("packaged MCP first-catalog budget while a phase is pending", () => {
|
||||
it("stops a pending initialize at the shorter first-catalog budget", async () => {
|
||||
const policy = probePolicy({
|
||||
initializeBudgetMs: MAX_NODE_TIMER_DELAY_MS,
|
||||
firstCatalogBudgetMs: 250,
|
||||
});
|
||||
let caught: unknown;
|
||||
try {
|
||||
await measureMcpStartup({
|
||||
command: process.execPath,
|
||||
args: [probeChild],
|
||||
environment: { ...process.env, REA_MCP_PROBE_MODE: "hang" },
|
||||
policy,
|
||||
it.each([
|
||||
[
|
||||
"initialize",
|
||||
"hang",
|
||||
{ initializeBudgetMs: MAX_NODE_TIMER_DELAY_MS },
|
||||
"REA_MCP_INITIALIZE_BUDGET_MS",
|
||||
],
|
||||
[
|
||||
"tools/list",
|
||||
"initialize-then-hang",
|
||||
{ toolsListBudgetMs: MAX_NODE_TIMER_DELAY_MS },
|
||||
"REA_MCP_TOOLS_LIST_BUDGET_MS",
|
||||
],
|
||||
] as const)(
|
||||
"stops a pending %s at the first-catalog budget",
|
||||
async (method, mode, phaseOverride, phaseSetting) => {
|
||||
const root = await createTestTempDirectory("rea-mcp-startup-");
|
||||
const marker = "pending-request";
|
||||
const path = join(root, marker);
|
||||
const policy = probePolicy({
|
||||
...phaseOverride,
|
||||
firstCatalogBudgetMs: 800,
|
||||
});
|
||||
} catch (cause) {
|
||||
caught = cause;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(Error);
|
||||
const message = errorMessage(caught);
|
||||
expectPhaseText(message, policy.firstCatalog);
|
||||
expect(message).not.toContain("REA_MCP_INITIALIZE_BUDGET_MS");
|
||||
});
|
||||
|
||||
it("stops a pending tools/list at the remaining first-catalog budget", async () => {
|
||||
const root = await createTestTempDirectory("rea-mcp-startup-");
|
||||
const initializedPath = join(root, "initialized");
|
||||
const policy = probePolicy({
|
||||
toolsListBudgetMs: MAX_NODE_TIMER_DELAY_MS,
|
||||
firstCatalogBudgetMs: 800,
|
||||
});
|
||||
let caught: unknown;
|
||||
try {
|
||||
await measureMcpStartup({
|
||||
const watcher = new AbortController();
|
||||
const pendingMethod = (async () => {
|
||||
for await (const event of watch(root, {
|
||||
signal: AbortSignal.any([
|
||||
watcher.signal,
|
||||
AbortSignal.timeout(testWaitDeadline()),
|
||||
]),
|
||||
})) {
|
||||
if (event.filename !== marker) continue;
|
||||
const requested = await readFile(path, "utf8").catch(
|
||||
(cause: unknown) => {
|
||||
if (
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
cause.code === "ENOENT"
|
||||
)
|
||||
return "";
|
||||
throw cause;
|
||||
},
|
||||
);
|
||||
if (requested.length > 0) return requested;
|
||||
}
|
||||
return undefined;
|
||||
})();
|
||||
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] });
|
||||
const clock = vi
|
||||
.spyOn(performance, "now")
|
||||
.mockImplementation(() => Date.now());
|
||||
const operation = measureMcpStartup({
|
||||
command: process.execPath,
|
||||
args: [probeChild],
|
||||
environment: {
|
||||
...process.env,
|
||||
REA_MCP_PROBE_MODE: "initialize-then-hang",
|
||||
REA_MCP_PROBE_INITIALIZED_PATH: initializedPath,
|
||||
REA_MCP_PROBE_MODE: mode,
|
||||
REA_MCP_PROBE_READY_PATH: path,
|
||||
},
|
||||
policy,
|
||||
});
|
||||
} catch (cause) {
|
||||
caught = cause;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(Error);
|
||||
const message = errorMessage(caught);
|
||||
expectPhaseText(message, policy.firstCatalog);
|
||||
expect(message).not.toContain("REA_MCP_TOOLS_LIST_BUDGET_MS");
|
||||
expect(await readFile(initializedPath, "utf8")).toBe("ready");
|
||||
});
|
||||
const settled = settledCause(operation);
|
||||
try {
|
||||
expect(await Promise.race([pendingMethod, settled])).toBe(method);
|
||||
await vi.advanceTimersByTimeAsync(policy.firstCatalog.milliseconds);
|
||||
const message = await expectThrownBudget(
|
||||
operation,
|
||||
policy.firstCatalog,
|
||||
);
|
||||
expect(message).not.toContain(phaseSetting);
|
||||
} finally {
|
||||
watcher.abort();
|
||||
await vi.advanceTimersByTimeAsync(policy.firstCatalog.milliseconds);
|
||||
await settled;
|
||||
clock.mockRestore();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("returns the catalog when every phase finishes inside its budget", async () => {
|
||||
const measurement = await measureMcpStartup({
|
||||
|
||||
+11
-6
@@ -35,15 +35,23 @@ input.on("line", (line) => {
|
||||
return;
|
||||
}
|
||||
if (request.id === undefined) return;
|
||||
if (mode === "hang") return;
|
||||
if (mode === "initialize-then-hang" && request.method !== "initialize")
|
||||
if (
|
||||
mode === "hang" ||
|
||||
(mode === "initialize-then-hang" && request.method !== "initialize")
|
||||
) {
|
||||
const readyPath = process.env.REA_MCP_PROBE_READY_PATH;
|
||||
if (readyPath !== undefined) writeFileSync(readyPath, request.method);
|
||||
return;
|
||||
}
|
||||
if (mode === "hang-on-call" && request.method === "tools/call") {
|
||||
const readyPath = process.env.REA_MCP_PROBE_READY_PATH;
|
||||
if (readyPath !== undefined) void writeFile(readyPath, "ready");
|
||||
return;
|
||||
}
|
||||
if (mode === "refuse-call" && request.method === "tools/call") {
|
||||
if (
|
||||
(mode === "refuse-call" && request.method === "tools/call") ||
|
||||
(mode === "refuse-list" && request.method === "tools/list")
|
||||
) {
|
||||
respond(request.id, undefined);
|
||||
return;
|
||||
}
|
||||
@@ -55,9 +63,6 @@ input.on("line", (line) => {
|
||||
capabilities: { tools: {}, prompts: {} },
|
||||
serverInfo: { name: "probe-fixture", version: "1" },
|
||||
};
|
||||
// Synchronous so a parent can observe initialize before the next phase hangs.
|
||||
if (process.env.REA_MCP_PROBE_INITIALIZED_PATH !== undefined)
|
||||
writeFileSync(process.env.REA_MCP_PROBE_INITIALIZED_PATH, "ready");
|
||||
break;
|
||||
case "tools/list":
|
||||
result = { tools: [] };
|
||||
|
||||
Reference in new issue
Block a user