Files
reverse-engineering-anything/tests/boundary/mcp/bundleComparisonCancellation.test.ts
T
morluto 858ff73880 perf(tests): give MCP test clients the shared lazy schema validation (#10960)
* perf(tests): give MCP test clients the shared lazy schema validation

The MCP SDK client compiles every listed tool's output schema on its
first tool call. With the SDK's default Ajv options, REA's catalog costs
gigabytes of allocation per client (inspect_analysis_view alone: 1.7 s and
~500 MiB retained), so native MCP files peaked at 1-2 GiB per worker.

tests/fixtures/mcpSchemaValidation already owns lazy, reference-preserving
validation. Route the native MCP, process-boundary and shared harness
clients through it, share compiled validators across clients in a worker
(bounded LRU keyed by schema text), and add a counted architecture guard so
default-validation test clients cannot spread; the remaining copies are the
baseline.

* fix(guards): read call arguments past parentheses inside string literals

* perf(tests): give MCP boundary test clients the shared schema validation (#11022)

* perf(tests): give MCP boundary test clients the shared schema validation

* perf(tests): give the remaining MCP test clients the shared schema validation (#11025)

* fix(guards): read an MCP client's validator option from parsed code

The default-validation counter searched each new Client(...) call's text for jsonSchemaValidator, so an inline comment, a string literal or a client name naming the option hid a default client. Parse the source with @babel/parser and count NewExpressions of Client whose object-literal arguments have no jsonSchemaValidator property; a source that does not parse counts every textual call. The guard reads raw test sources, and the generated-child-script allowlist entry, which no longer counts as a call, is removed.

* fix(guards): read an MCP client's options only from a whole object-literal argument

The default-validation counter skipped files without the text
'new Client(', so a comment between the tokens hid a client, and it took
any depth-two key as an option, so 'enabled ? { jsonSchemaValidator } : {}'
passed while its false branch uses the SDK default. The skip now only
requires the name Client, and the validator counts only when it is a key
of an object literal that is a whole argument; anything else counts as the
default.
2026-11-15 21:53:53 -05:00

171 lines
5.9 KiB
TypeScript

import { unknownTarget } from "../../../src/domain/targetIdentity.js";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, onTestFinished, vi } from "vitest";
import { phaseArrival } from "../../support/lifecycleHarness.js";
import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import {
createEvidenceBundle,
serializeEvidenceBundle,
} from "../../../src/domain/evidenceBundle.js";
import { createServer } from "../../../src/server/createServer.js";
import { ToolResultDelivery } from "../../../src/server/ToolResultDelivery.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { holdFirstFileRead } from "../../support/holdFirstFileRead.js";
import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js";
it("leaves the session unchanged after bundle comparison cancellation and permits a retry", async () => {
const root = await createTestTempDirectory("rea-mcp-compare-cancel-");
const leftPath = join(root, "left.json");
const rightPath = join(root, "right.json");
const provider = { id: "fixture", name: "Fixture", version: "1" };
const left = createEvidence(unknownTarget("not-observed"), provider, {
operation: "observation",
parameters: { side: "left" },
result: { side: "left" },
});
const right = createEvidence(unknownTarget("not-observed"), provider, {
operation: "observation",
parameters: { side: "right" },
result: { side: "right" },
});
const leftContents =
" ".repeat(8 * 1024 * 1024) +
serializeEvidenceBundle(createEvidenceBundle([left]));
await Promise.all([
// Just over the native-parse budget, without a large JSON tree.
writeFile(leftPath, leftContents),
writeFile(
rightPath,
serializeEvidenceBundle(createEvidenceBundle([right])),
),
]);
const session = createTestBinarySession(() => {
throw new Error("Bundle comparison must not start a binary provider");
});
const existing = createEvidence(unknownTarget("not-observed"), provider, {
operation: "existing_observation",
parameters: {},
result: { retained: true },
});
const recorded = session.recordEvidence(existing);
if (!recorded.ok) throw recorded.error;
const before = session.exportEvidenceBundle();
const server = createServer({ kind: "session", session });
const client = new Client(
{
name: "bundle-comparison-cancellation",
version: "1",
},
{ jsonSchemaValidator: createMcpSchemaValidation() },
);
const controller = new AbortController();
let releaseRead: (() => void) | undefined;
onTestFinished(async () => {
controller.abort();
releaseRead?.();
vi.restoreAllMocks();
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const reader = await holdFirstFileRead(leftPath);
releaseRead = reader.release;
const dispatch = phaseArrival();
const send = clientTransport.send.bind(clientTransport);
vi.spyOn(clientTransport, "send").mockImplementation(
async (message, ...args) => {
await send(message, ...args);
if ("method" in message && message.method === "tools/call")
dispatch.arrive();
},
);
let resolveCompleted: (() => void) | undefined;
const completed = new Promise<void>((resolve) => {
resolveCompleted = resolve;
});
let settledResult: unknown;
const deliver = ToolResultDelivery.prototype.toCallToolResult;
vi.spyOn(ToolResultDelivery.prototype, "toCallToolResult").mockImplementation(
function (this: ToolResultDelivery, result, contract) {
const reply = deliver.call(this, result, contract);
if (contract.name === "compare_bundles") {
settledResult = result;
resolveCompleted?.();
}
return reply;
},
);
const args = {
left_bundle_path: leftPath,
right_bundle_path: rightPath,
record_pairs: [
{
left_evidence_id: left.evidence_id,
right_evidence_id: right.evidence_id,
},
],
};
const cancellation = client
.callTool(
{ name: "compare_bundles", arguments: args },
{ signal: controller.signal },
)
.then(
() => "completed",
(error: unknown) => error,
);
await dispatch.reached(cancellation, "compare_bundles dispatch");
await reader.reached(cancellation, "first file read");
await client.ping();
controller.abort(new Error("SDK bundle comparison cancellation"));
reader.release();
expect(await cancellation).toMatchObject({
message: expect.stringContaining("SDK bundle comparison cancellation"),
});
// Wait for the handler's delivered Result as well as the client's rejection.
await completed;
expect(settledResult).toMatchObject({
ok: false,
error: expect.any(AnalysisCancelledError),
});
expect(reader.readCount).toBe(1);
expect(reader.totalReadBytes).toBeLessThan(leftContents.length);
expect(session.exportEvidenceBundle()).toEqual(before);
await client.ping();
const retry = await client.callTool({
name: "compare_bundles",
arguments: args,
});
expect(retry.isError, JSON.stringify(retry)).not.toBe(true);
expect(retry.structuredContent).toMatchObject({
normalized_result: { status: "changed" },
});
const after = session.exportEvidenceBundle();
expect(after.unknowns).toEqual(before.unknowns);
expect(after.records).toEqual(
expect.arrayContaining([
...before.records,
left,
right,
expect.objectContaining({
operation: "compare_bundles",
evidence_links: [left.evidence_id, right.evidence_id],
}),
]),
);
});