Repository navigation
perf(mcp): advertise large output union alternatives as shared definitions - #11005
Conversation
…tions inspect_analysis_view's advertised output schema held every view result inline in one union definition, which the MCP SDK's default validator compiled into one function: about 1.7 s CPU and 500 MiB peak. Large union alternatives now become definitions of their own and identical definitions are merged, at the owning output projection. Tests that check results against the advertised output contract now compile that schema instead of a separate inline projection, which overflowed the main-thread stack under forked workers.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
[Medium impact] The PR appears safe to merge; the previous repository-rule finding is fixed and no new actionable issue was found. SummaryThe PR moves large output union alternatives into shared definitions and merges duplicate definitions before calculating the advertised schema’s identity. It also switches five source test projects to forked workers.
Diagram%%{init: {'theme': 'neutral'}}%%
flowchart LR
A["Canonical output schema"] --> B["presentOutputJsonSchema"]
B --> C["Hoist large alternatives"]
C --> D["Merge identical definitions"]
D --> E["Calculate content-bound $id"]
E --> F["Advertised schema and catalog identity"]
Reviews (3) · Last reviewed commit: "test(mcp): select the analysis view cont..." · Reviewed by Greptile |
Thread workers of the source lane share one process, which grew to 3.8-5.0 GiB; forked workers keep each heap separate so the largest process stays near 1.2-1.8 GiB.
…ration (#11057) #11005 left two exported declarations of advertisedOutputJsonSchema in src/contracts/toolSchemaMetadata.ts, so main no longer typechecks (TS2451). The second declaration takes an optional target that defaults to the first one's fixed draft-2020-12, so it covers every caller. The first is removed and its documentation moves onto the remaining one.
Summary
The advertised output schema for
inspect_analysis_viewput every view result inline in one union definition. Ajv-based validators, including the MCP SDK client's default one, compile that union into a single function. Large union alternatives now become definitions of their own, and identical definitions are merged, both in the output projection that owns the advertised schema. For this tool's schema, SDK compile peak memory drops from about 500 to 186 MiB and CPU from 1.7 to 0.8 s. The schema also gets 3% smaller.Two tests that check results "within the advertised output contract" were compiling a different, fully inline projection of 1.5 MB. Its single validator function needs a stack frame larger than the main thread's default stack. They now compile the advertised schema, so they also pass in forked workers (forked workers are the follow-up change to the source test lanes).
Problem and expected behavior
inspect_analysis_view's advertised output had 1,108$defs. One of them (normalized_result, 442 KB) was ananyOfover every view result, with each alternative inline. Every MCP client that validates output compiles it. With the SDK's defaultAjvJsonSchemaValidator, it took a median 1.7 s CPU and 498 MiB peak RSS growth, measured below.src/contracts/analysisDetail.test.tsandsrc/application/analysisView/BrowserScenarioViews.test.tscompiledz.toJSONSchema(contract.outputSchema). That is Zod's default inline projection: 1.5 MB with no$defs, which is not what REA advertises. Underpool: "forks", both fail withRangeError: Maximum call stack size exceededin a single generatedvalidateNNframe, with no recursion involved. Under threads, the 4 MiB worker stack hid this.Expected: clients compile REA's advertised output schemas in bounded pieces, and tests check results against the schema REA advertises.
Change and scope
This PR now also contains #11016, which was collapsed into this branch. The source test projects (
domain,services,composition,conformance,evaluation) run inforksworkers, still withisolate: false. That change and its source-lane measurements are in #11016: the largest single process dropped from 5.0 GiB to 1.2–1.8 GiB, total family RSS stayed about 5 GiB, and all 1,591 files passed in both cold and warm runs. The stack-overflow fix below is what makes the forked lane pass.src/contracts/outputSchemaDefinitions.ts(new) owns the layout of the advertised output schema:anyOf/oneOfalternative that serializes to more than 1 KiB becomes a definition (__branchN). A reference plus a definition entry costs about 45 bytes, so smaller alternatives stay inline.$refin a schema position is#/$defs/<plain name>(or#/definitions/<plain name>for draft-07) naming an existing definition, and no$id,$anchor,$dynamic*or$recursive*changes resolution. Instance values (const,enum,default,examples) and unknown keywords are never rewritten.toolOutputSchemaWithMetadataapplies it afterpresentOutputJsonSchemaand before the content-bound$iddigest, so the$idcovers the final layout.advertisedOutputJsonSchema(contract, target)mirrorsadvertisedInputJsonSchema.catalogIdentity, the two tests above andprogressiveAnalysisViews.test.tsuse it instead of reaching into~standard.Not included:
__schemaNdefinitions to shorter names, which would save more bytes but changes every tool's schema text.Coordination: #10718 (W3 stack) changes the same
toolOutputSchemaWithMetadatablock (objectRoot). The conflict is limited to wrapping thepresentOutputJsonSchema(...)call. The client-engine checks (#10982–#10986) do not touch the generator.Contract and boundary impact
src/contracts/outputSchemaDefinitions.ts, called from the advertised output projection intoolSchemaMetadata.ts. The SDK registration, catalog identity and recorded catalog consume that projection unchanged.$defslayout and$iddigest, and catalog digests change with them. What the schemas accept is unchanged, and canonical runtime validation is untouched. Recorded catalog digests are generated at build time.Expected effects:
Evidence and regression coverage
Executed on macOS (arm64, Node 24.22.1, MCP SDK client default
AjvJsonSchemaValidator). Each output schema was taken fromtools/listthrough the real SDKClientoverInMemoryTransport, then compiled in a fresh process. Before and after runs were interleaved, 5 runs each, on a shared host with load average 12–20 on 10 cores. Values are medians, with ranges where noted. Peak ismaxRSSgrowth over the process RSS before compiling.$defsinspect_analysis_viewbeforeinspect_analysis_viewafterRetained heap after compiling is unchanged (16 → 15 MiB for the tool, 77 → 76 MiB for the catalog). Bytes count serialized JSON characters; agent tokens were not measured. Server side, projecting all 255 output schemas once costs about 0.3 s more CPU (median of 3: 0.83 → 1.15 s). This happens once per process: the projection is memoized per contract and target, and deferred startup serves the recorded catalog.
src/contracts/outputSchemaDefinitions.test.tscovers:$defs/2020-12 anddefinitions/draft-07, with valid and invalid samples compared before and after;$id, anchor,$dynamicRef, a non-definition pointer, an external reference, an unknown name, an escaped pointer, zero or two definition maps);inspect_analysis_viewschema.domain/servicesset topool: "forks"in a local, uncommitted config edit, the base versions ofanalysisDetail.test.tsandBrowserScenarioViews.test.tsfail withRangeError: Maximum call stack size exceeded, 2 of 2. With this change, the same run passes 2 files / 15 tests.For evidence-bearing changes:
Validation performed
npm run test:local -- src/contracts/outputSchemaDefinitions.test.ts src/contracts/analysisDetail.test.ts src/application/analysisView/BrowserScenarioViews.test.ts src/contracts/toolOutputReferences.test.ts src/contracts/toolSchemaMetadata.test.ts src/contracts/canonicalBase64Metadata.test.ts: 6 files / 68 tests passed (6.5 s wall, 1.2 GiB peak).npm run test:focused -- tests/boundary/mcp/outputSchemaProfile.test.ts tests/boundary/mcp/generatedToolCatalog.test.ts tests/boundary/mcp/toolSchemaValidity.test.ts tests/boundary/mcp/advertisedDialect.test.ts tests/boundary/mcp/advertisedMcpTool.test.ts tests/boundary/mcp/outputValidatorReuse.test.ts tests/boundary/mcp/deferredRuntime.test.ts tests/boundary/mcp/packageCatalogVerification.test.ts tests/acceptance/applications/progressiveAnalysisViews.test.ts: 98 passed and 2 failed, with the sameinput keyword const: 1859 > 1857input-dialect count inadvertisedDialectandpackageCatalogVerification.advertisedDialectfails the same way with this change disabled, and this change touches only output schemas.domain/serviceslocally switched to forks,node node_modules/vitest/vitest.mjs run src/contracts/analysisDetail.test.ts src/application/analysisView/BrowserScenarioViews.test.tsfailed with the base tests (2RangeError) and passed with this change (2 files / 15 tests).npm run check:fast,node scripts/verify/architecture-guards.mjsandnpx oxfmt --checkon the changed files all passed.Review follow-up (454bc97):
outputSchemaDefinitions.test.tsselectsinspect_analysis_viewfromANALYSIS_VIEW_TOOL_CONTRACTS.npm run test:local -- src/contracts/outputSchemaDefinitions.test.tspassed 14 tests, andnpm run check:fastpassed.Compatibility, safety, and release
Author readiness
Human owner:
Before merge
type(scope): outcome.