mirror of
https://github.com/morluto/rea.git
synced 2026-11-22 22:45:47 +00:00
perf(cli/mcp): eliminate eager JSON schema work, double projection, and O(N^2) error compaction (#13466)
* perf(cli/mcp): eliminate eager JSON schema work, double projection, and O(N^2) error compaction (#13464) * test(mcp): cover reuse of the registration input schema projection
This commit is contained in:
1 parent
99c42ddc46
commit
8688eb0195
13 files changed
+204
-67
No files matched your search
@@ -1,7 +1,7 @@
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { analysisErrorJsonSchema } from "../dist/contracts/errorSchemas.js";
|
||||
import { analysisErrorJsonSchema } from "../dist/contracts/analysisErrorJsonSchema.js";
|
||||
import { analysisErrorCatalogue } from "../dist/domain/analysisErrorClassification.js";
|
||||
import { hopperErrorCatalogue } from "../dist/hopper/HopperErrors.js";
|
||||
import { formatGeneratedFile } from "./lib/format-generated-file.mjs";
|
||||
|
||||
@@ -48,20 +48,37 @@ const openEndedPattern = (minimum: number): string => {
|
||||
* it never rejects a token the parser admits.
|
||||
*/
|
||||
export const decimalTokenPattern = (domain: z.ZodNumber): string => {
|
||||
const schema = z.toJSONSchema(domain);
|
||||
const minimum = Math.max(
|
||||
0,
|
||||
Math.ceil(schema.minimum ?? 0),
|
||||
typeof schema.exclusiveMinimum === "number"
|
||||
? Math.floor(schema.exclusiveMinimum) + 1
|
||||
: 0,
|
||||
);
|
||||
const maximum = Math.min(
|
||||
Math.floor(schema.maximum ?? Infinity),
|
||||
typeof schema.exclusiveMaximum === "number"
|
||||
? Math.ceil(schema.exclusiveMaximum) - 1
|
||||
: Infinity,
|
||||
);
|
||||
let minimum =
|
||||
domain.minValue !== null && domain.minValue > 0
|
||||
? Math.ceil(domain.minValue)
|
||||
: 0;
|
||||
let maximum =
|
||||
domain.maxValue !== null && domain.maxValue < Infinity
|
||||
? Math.floor(domain.maxValue)
|
||||
: Infinity;
|
||||
for (const check of domain._zod.def.checks ?? []) {
|
||||
const def = check._zod.def as {
|
||||
readonly check?: string;
|
||||
readonly value?: unknown;
|
||||
readonly inclusive?: boolean;
|
||||
};
|
||||
if (typeof def.value !== "number") continue;
|
||||
if (def.check === "greater_than") {
|
||||
minimum = Math.max(
|
||||
minimum,
|
||||
def.inclusive === false
|
||||
? Math.floor(def.value) + 1
|
||||
: Math.ceil(def.value),
|
||||
);
|
||||
} else if (def.check === "less_than") {
|
||||
maximum = Math.min(
|
||||
maximum,
|
||||
def.inclusive === false
|
||||
? Math.ceil(def.value) - 1
|
||||
: Math.floor(def.value),
|
||||
);
|
||||
}
|
||||
}
|
||||
// Non-integer floors and ceilings have no safe-integer range to publish.
|
||||
if (!Number.isSafeInteger(minimum)) return "^[0-9]+$";
|
||||
if (maximum === Infinity) return openEndedPattern(minimum);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { z } from "zod";
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { decimalTokenPattern } from "./cli/decimalTokenPattern.js";
|
||||
import { cliDecimalField } from "./cli/options.js";
|
||||
|
||||
it("keeps advertised decimal bounds aligned across decimal-width transitions", () => {
|
||||
@@ -102,3 +103,51 @@ it("keeps a positive floor when the domain has no ceiling", () => {
|
||||
expect(validate("")).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("derives decimal token bounds matching z.toJSONSchema across ZodNumber shapes", () => {
|
||||
const domains = [
|
||||
z.number(),
|
||||
z.number().int(),
|
||||
z.int32(),
|
||||
z.uint32(),
|
||||
z.number().min(5).max(10),
|
||||
z.number().gt(0).lt(100),
|
||||
z.number().positive(),
|
||||
z.number().nonnegative(),
|
||||
z.number().min(1.5).max(9.5),
|
||||
z.number().gt(1.5).lt(9.5),
|
||||
z.number().max(-1),
|
||||
z.number().min(10).max(5),
|
||||
] as const;
|
||||
for (const domain of domains) {
|
||||
const schema = z.toJSONSchema(domain);
|
||||
const expectedMin = Math.max(
|
||||
0,
|
||||
Math.ceil(schema.minimum ?? 0),
|
||||
typeof schema.exclusiveMinimum === "number"
|
||||
? Math.floor(schema.exclusiveMinimum) + 1
|
||||
: 0,
|
||||
);
|
||||
const expectedMax = Math.min(
|
||||
Math.floor(schema.maximum ?? Infinity),
|
||||
typeof schema.exclusiveMaximum === "number"
|
||||
? Math.ceil(schema.exclusiveMaximum) - 1
|
||||
: Infinity,
|
||||
);
|
||||
const regex = new RegExp(decimalTokenPattern(domain), "u");
|
||||
if (expectedMin > expectedMax) {
|
||||
expect(regex.test("0")).toBe(false);
|
||||
expect(regex.test("5")).toBe(false);
|
||||
continue;
|
||||
}
|
||||
if (Number.isSafeInteger(expectedMin)) {
|
||||
expect(regex.test(String(expectedMin))).toBe(true);
|
||||
if (expectedMin > 0)
|
||||
expect(regex.test(String(expectedMin - 1))).toBe(false);
|
||||
}
|
||||
if (Number.isSafeInteger(expectedMax)) {
|
||||
expect(regex.test(String(expectedMax))).toBe(true);
|
||||
expect(regex.test(String(expectedMax + 1))).toBe(false);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { analysisErrorProjectionSchema } from "../domain/analysisErrorProjectionSchema.js";
|
||||
|
||||
/** JSON Schema document used by generated API documentation and clients. */
|
||||
export const analysisErrorJsonSchema = z.toJSONSchema(
|
||||
analysisErrorProjectionSchema,
|
||||
);
|
||||
@@ -28,8 +28,3 @@ export const analysisCliErrorEnvelopeSchema = z
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/** JSON Schema document used by generated API documentation and clients. */
|
||||
export const analysisErrorJsonSchema = z.toJSONSchema(
|
||||
analysisErrorProjectionSchema,
|
||||
);
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Ajv, type Options } from "ajv";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { applicationFeatureSeedSchema } from "../domain/javascript/javascriptFeatureTraceSchemas.js";
|
||||
@@ -55,10 +55,22 @@ it.each(drafts)(
|
||||
});
|
||||
const options = { target, libraryOptions: { reused: "ref" as const } };
|
||||
for (const sharedFirst of [false, true]) {
|
||||
const wrapped = transformAdvertisedInputJsonSchema(canonical, transform);
|
||||
const seed = transform(
|
||||
canonical["~standard"].jsonSchema.input({ target }),
|
||||
);
|
||||
const resolveCached = vi.fn(() => seed);
|
||||
const wrapped = transformAdvertisedInputJsonSchema(
|
||||
canonical,
|
||||
transform,
|
||||
resolveCached,
|
||||
);
|
||||
const project = wrapped["~standard"].jsonSchema.input;
|
||||
if (sharedFirst) project(options);
|
||||
if (sharedFirst) {
|
||||
project(options);
|
||||
expect(resolveCached).not.toHaveBeenCalled();
|
||||
}
|
||||
const advertised = project({ target });
|
||||
expect(advertised).toBe(seed);
|
||||
expect(JSON.stringify(advertised)).not.toContain('"$ref":');
|
||||
expect(advertised).toEqual(
|
||||
transform(canonical["~standard"].jsonSchema.input({ target })),
|
||||
@@ -69,6 +81,7 @@ it.each(drafts)(
|
||||
transform(canonical["~standard"].jsonSchema.input(options)),
|
||||
);
|
||||
expect(project({ target })).toBe(advertised);
|
||||
expect(resolveCached).toHaveBeenCalledExactlyOnceWith(target);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -277,6 +277,7 @@ export const omitAdvertisedOutputJsonSchema = <Schema>(
|
||||
export const transformAdvertisedInputJsonSchema = <Schema>(
|
||||
schema: Schema,
|
||||
transform: (projected: Record<string, unknown>) => Record<string, unknown>,
|
||||
resolveCached?: (target: string) => Record<string, unknown> | undefined,
|
||||
): Schema => {
|
||||
const standard = Reflect.get(schema as object, "~standard");
|
||||
if (!isRecord(standard)) return schema;
|
||||
@@ -293,6 +294,11 @@ export const transformAdvertisedInputJsonSchema = <Schema>(
|
||||
if (cacheable) {
|
||||
const cached = byTarget.get(target);
|
||||
if (cached !== undefined) return cached;
|
||||
const seeded = resolveCached?.(target);
|
||||
if (seeded !== undefined) {
|
||||
byTarget.set(target, seeded);
|
||||
return seeded;
|
||||
}
|
||||
}
|
||||
const projected = (project as (options: unknown) => unknown)(options);
|
||||
const transformed = isRecord(projected) ? transform(projected) : projected;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
Client,
|
||||
InMemoryTransport,
|
||||
@@ -677,6 +677,52 @@ describe("SDK argument name guidance", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("reuses the tool registration input projection across SDK listings", async () => {
|
||||
const server = new EvidenceMcpServer(
|
||||
{ name: "input-projection-server", version: "1" },
|
||||
{ capabilities: {} },
|
||||
undefined,
|
||||
createToolResultDelivery(4096),
|
||||
);
|
||||
const schema = z.strictObject({ value: z.string() });
|
||||
const standard = schema["~standard"];
|
||||
const input = vi.fn(standard.jsonSchema.input);
|
||||
Object.defineProperty(schema, "~standard", {
|
||||
value: { ...standard, jsonSchema: { ...standard.jsonSchema, input } },
|
||||
});
|
||||
server.registerTool(
|
||||
"counted_input",
|
||||
{ description: "Count input projections", inputSchema: schema },
|
||||
async () => ({ content: [] }),
|
||||
);
|
||||
expect(input).toHaveBeenCalledExactlyOnceWith({ target: "draft-2020-12" });
|
||||
|
||||
const client = new Client({ name: "input-projection-client", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
const serving = serveStdio(() => server, { transport: serverTransport });
|
||||
try {
|
||||
await client.connect(clientTransport);
|
||||
const first = await client.listTools();
|
||||
expect(first.tools).toMatchObject([
|
||||
{
|
||||
name: "counted_input",
|
||||
description: "Count input projections",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { value: { type: "string" } },
|
||||
required: ["value"],
|
||||
},
|
||||
},
|
||||
]);
|
||||
expect(input).toHaveBeenCalledTimes(1);
|
||||
expect(await client.listTools()).toEqual(first);
|
||||
expect(input).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
await Promise.all([client.close(), serving.close()]);
|
||||
}
|
||||
});
|
||||
|
||||
it("skips object-root output schema projection on output=off while keeping runtime validation and legacy wrapping", async () => {
|
||||
const server = new EvidenceMcpServer(
|
||||
{ name: "output-off-skip-test", version: "1" },
|
||||
|
||||
@@ -533,19 +533,32 @@ export class EvidenceMcpServerCore extends RequestTrackingMcpServer {
|
||||
const { input } = this.presentation;
|
||||
if (inputSchema === undefined || !hasAdvertisedInputJsonSchema(inputSchema))
|
||||
return config;
|
||||
let draft2020:
|
||||
| {
|
||||
readonly description: string | undefined;
|
||||
readonly inputSchema: Record<string, unknown> | undefined;
|
||||
}
|
||||
| undefined;
|
||||
const projectDraft2020 = () => {
|
||||
if (draft2020 !== undefined) return draft2020;
|
||||
const projected = (inputSchema as StandardSchemaWithJSON)[
|
||||
"~standard"
|
||||
].jsonSchema.input({ target: "draft-2020-12" });
|
||||
draft2020 = isRecord(projected)
|
||||
? advertiseToolInput(description, projected, input)
|
||||
: { description, inputSchema: undefined };
|
||||
return draft2020;
|
||||
};
|
||||
return {
|
||||
...this.describeTool(name, () => {
|
||||
const projected = (inputSchema as StandardSchemaWithJSON)[
|
||||
"~standard"
|
||||
].jsonSchema.input({ target: "draft-2020-12" });
|
||||
return isRecord(projected)
|
||||
? advertiseToolInput(description, projected, input).description
|
||||
: description;
|
||||
}),
|
||||
...this.describeTool(name, () => projectDraft2020().description),
|
||||
inputSchema: transformAdvertisedInputJsonSchema(
|
||||
inputSchema,
|
||||
(projected) =>
|
||||
advertiseToolInput(description, projected, input).inputSchema,
|
||||
(target) =>
|
||||
target === "draft-2020-12"
|
||||
? projectDraft2020().inputSchema
|
||||
: undefined,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -190,7 +190,7 @@ describe("error delivery omission worklist", () => {
|
||||
);
|
||||
expect(result.content).toHaveLength(1);
|
||||
expect(first.reads()).toBe(3);
|
||||
expect(second.reads()).toBe(3);
|
||||
expect(second.reads()).toBe(2);
|
||||
expect(
|
||||
(
|
||||
result.structuredContent as {
|
||||
|
||||
@@ -439,38 +439,28 @@ export class ToolResultDelivery {
|
||||
}))
|
||||
.sort((left, right) => right.size - left.size)
|
||||
.map(({ candidate }) => candidate);
|
||||
while (!encoded.ok && remaining.length > 0) {
|
||||
const limit = encoded;
|
||||
let next: AnalysisErrorProjection | undefined;
|
||||
let nextIndex = -1;
|
||||
for (const [index, candidate] of remaining.entries()) {
|
||||
const compact = omitUnretainedEvidenceFromError(
|
||||
candidateProjection,
|
||||
limit,
|
||||
candidate,
|
||||
);
|
||||
if (compact === undefined) continue;
|
||||
if (next === undefined) {
|
||||
next = compact;
|
||||
nextIndex = index;
|
||||
}
|
||||
const content = { error: compact };
|
||||
const compactEncoded = encodeToolResult(
|
||||
content,
|
||||
this.resultBudgetBytes,
|
||||
"error-text",
|
||||
targetContent,
|
||||
);
|
||||
if (compactEncoded.ok) {
|
||||
structuredContent = content;
|
||||
encoded = compactEncoded;
|
||||
break;
|
||||
}
|
||||
let index = 0;
|
||||
while (!encoded.ok && index < remaining.length) {
|
||||
const compact = omitUnretainedEvidenceFromError(
|
||||
candidateProjection,
|
||||
encoded,
|
||||
remaining[index]!,
|
||||
);
|
||||
index += 1;
|
||||
if (compact === undefined) continue;
|
||||
candidateProjection = compact;
|
||||
const content = { error: compact };
|
||||
const compactEncoded = encodeToolResult(
|
||||
content,
|
||||
this.resultBudgetBytes,
|
||||
"error-text",
|
||||
targetContent,
|
||||
);
|
||||
if (compactEncoded.ok) {
|
||||
structuredContent = content;
|
||||
encoded = compactEncoded;
|
||||
break;
|
||||
}
|
||||
if (encoded.ok) break;
|
||||
if (next === undefined) break;
|
||||
candidateProjection = next;
|
||||
remaining.splice(nextIndex, 1);
|
||||
}
|
||||
}
|
||||
// The transport retains an oversized projected error before replacing it
|
||||
|
||||
@@ -19,7 +19,7 @@ import type { ToolContract } from "../contracts/toolContractTypes.js";
|
||||
import { ok } from "../domain/result.js";
|
||||
import type { RecoveryAdmission } from "../application/investigation/InvestigationRetention.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
|
||||
import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { ownedJsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
|
||||
import { mcpProgressReporter } from "./mcpProgress.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
@@ -84,7 +84,7 @@ export const createProviderOperationToolHandler =
|
||||
input: unknown,
|
||||
context: ServerContext,
|
||||
): Promise<CallToolResult> => {
|
||||
const resolved = jsonObjectSchema.parse(input);
|
||||
const resolved = ownedJsonObjectSchema.parse(input);
|
||||
const parameters =
|
||||
currentMcpToolRequest()?.callerParameters(
|
||||
contract.name,
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
|
||||
import { ProcessCaptureError } from "../../../src/process/capture/ProcessCaptureError.js";
|
||||
import { analysisErrorJsonSchema } from "../../../src/contracts/errorSchemas.js";
|
||||
import { analysisErrorJsonSchema } from "../../../src/contracts/analysisErrorJsonSchema.js";
|
||||
import { analysisErrorProjectionSchema } from "../../../src/domain/analysisErrorProjectionSchema.js";
|
||||
import { ArtifactOperationError } from "../../../src/domain/artifactOperationError.js";
|
||||
import { EvidenceFileError } from "../../../src/domain/evidenceErrors.js";
|
||||
|
||||
Reference in new issue
Block a user