Skip to content

perf(mcp): advertise large output union alternatives as shared definitions - #11005

Merged
morluto merged 3 commits into
mainfrom
perf/mcp-output-schema-definitions
Nov 15, 2026
Merged

morluto merged 3 commits into
mainfrom
perf/mcp-output-schema-definitions

Conversation

@morluto

@morluto morluto commented Nov 15, 2026 •

Copy link
Copy Markdown
Owner

Summary

The advertised output schema for inspect_analysis_view put 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 an anyOf over every view result, with each alternative inline. Every MCP client that validates output compiles it. With the SDK's default AjvJsonSchemaValidator, it took a median 1.7 s CPU and 498 MiB peak RSS growth, measured below.
  • src/contracts/analysisDetail.test.ts and src/application/analysisView/BrowserScenarioViews.test.ts compiled z.toJSONSchema(contract.outputSchema). That is Zod's default inline projection: 1.5 MB with no $defs, which is not what REA advertises. Under pool: "forks", both fail with RangeError: Maximum call stack size exceeded in a single generated validateNN frame, 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 in forks workers, still with isolate: 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:
    • Each anyOf/oneOf alternative 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.
    • Definitions that are identical after this are merged, repeating until none remain identical. A merge can make the definitions that referenced the merged ones identical too.
    • It fails closed: a schema is returned unchanged unless every $ref in 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.
  • toolOutputSchemaWithMetadata applies it after presentOutputJsonSchema and before the content-bound $id digest, so the $id covers the final layout.
  • advertisedOutputJsonSchema(contract, target) mirrors advertisedInputJsonSchema. catalogIdentity, the two tests above and progressiveAnalysisViews.test.ts use it instead of reaching into ~standard.

Not included:

Coordination: #10718 (W3 stack) changes the same toolOutputSchemaWithMetadata block (objectRoot). The conflict is limited to wrapping the presentOutputJsonSchema(...) call. The client-engine checks (#10982–#10986) do not touch the generator.

Contract and boundary impact

  • Semantic owner and earliest changed stage: src/contracts/outputSchemaDefinitions.ts, called from the advertised output projection in toolSchemaMetadata.ts. The SDK registration, catalog identity and recorded catalog consume that projection unchanged.
  • Contribution scope fit and linked maintainer decision: not applicable (presentation within the existing MCP contract).
  • CLI and MCP/tool-catalog contract: advertised output schemas change their $defs layout and $id digest, 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.
  • Provider, bridge, target-format, or platform compatibility: none.
  • Evidence, artifact, provenance, or reconstruction contract: none.
  • Target selection, authority, upstream behavior, and cleanup details: not applicable.
  • Generated metadata, package, or installation impact: the generated MCP catalog and product catalog regenerate with new output schema text. No committed files change.

Expected effects:

  • Read existing files or captured data.
  • Launch or attach to a process.
  • Inject instrumentation or run scripts/code.
  • Change process memory, registers, files, or configuration.
  • Contact network services.
  • Recover protected code or work around protections.
  • Documentation or usability only; no target interaction.
  • Not sure yet; investigation or maintainer guidance needed.

Evidence and regression coverage

Executed on macOS (arm64, Node 24.22.1, MCP SDK client default AjvJsonSchemaValidator). Each output schema was taken from tools/list through the real SDK Client over InMemoryTransport, 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 is maxRSS growth over the process RSS before compiling.

Case Bytes $defs Compile CPU Compile wall Peak RSS growth
inspect_analysis_view before 724,477 1,108 1.72 s (1.33–2.03) 1.01 s 498 MiB (448–501)
inspect_analysis_view after 702,675 830 0.84 s (0.68–1.17) 0.61 s 186 MiB (182–186)
All 255 output schemas, one SDK provider, before 4,291,806 12,236 4.16 s 3.48 s 647 MiB (615–687)
All 255 output schemas, one SDK provider, after 4,182,326 10,294 3.23 s 2.77 s 329 MiB (302–341)

Retained 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.

  • Tests added or updated: src/contracts/outputSchemaDefinitions.test.ts covers:
    • layout and unchanged validation for $defs/2020-12 and definitions/draft-07, with valid and invalid samples compared before and after;
    • transitive merging, and literal values and unknown keywords left as data;
    • fresh names that avoid existing definitions;
    • each fail-closed condition (embedded $id, anchor, $dynamicRef, a non-definition pointer, an external reference, an unknown name, an escaped pointer, zero or two definition maps);
    • a structural bound on the real inspect_analysis_view schema.
  • Base reproduction: with domain/services set to pool: "forks" in a local, uncommitted config edit, the base versions of analysisDetail.test.ts and BrowserScenarioViews.test.ts fail with RangeError: Maximum call stack size exceeded, 2 of 2. With this change, the same run passes 2 files / 15 tests.
  • Remaining proof gaps: client engines other than Ajv were not measured; the portable-engine checks in test(mcp): compile advertised patterns with the regex engines clients run #10982+ cover loading. Linux was not measured.

For evidence-bearing changes:

  • Observed, derived, and inferred claims remain distinguishable.
  • Artifact identity, source provenance, and failed attempts remain preserved.
  • Unsupported, incomplete, unavailable, or uncertain outcomes remain visible.

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 same input keyword const: 1859 > 1857 input-dialect count in advertisedDialect and packageCatalogVerification. advertisedDialect fails the same way with this change disabled, and this change touches only output schemas.
  • With domain/services locally switched to forks, node node_modules/vitest/vitest.mjs run src/contracts/analysisDetail.test.ts src/application/analysisView/BrowserScenarioViews.test.ts failed with the base tests (2 RangeError) and passed with this change (2 files / 15 tests).
  • npm run check:fast, node scripts/verify/architecture-guards.mjs and npx oxfmt --check on the changed files all passed.

Review follow-up (454bc97): outputSchemaDefinitions.test.ts selects inspect_analysis_view from ANALYSIS_VIEW_TOOL_CONTRACTS. npm run test:local -- src/contracts/outputSchemaDefinitions.test.ts passed 14 tests, and npm run check:fast passed.

Compatibility, safety, and release

  • Breaking changes or migration steps: none. Advertised output schemas accept the same values. Clients that pinned an output schema digest see a new one, as with any catalog change.
  • Real Hopper/Ghidra, browser, or OS coverage: not applicable; macOS only.
  • Package or release metadata impact: catalog digests change at build.
  • Security, privacy, process, or containment review: none.

Author readiness

Human owner:

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

…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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-15T10:21:57.932954Z c07c5bd New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@greptile-apps

greptile-apps Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5 Tier: plus

[Medium impact] The PR appears safe to merge; the previous repository-rule finding is fixed and no new actionable issue was found.

Summary

The 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.

  • Large output-schema alternatives now sit in shared definitions.
  • Shared source test projects now run in 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"]
Loading

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.
@morluto
morluto merged commit 7181e7f into main Nov 15, 2026
14 of 17 checks passed
@morluto
morluto deleted the perf/mcp-output-schema-definitions branch November 15, 2026 11:13
morluto added a commit that referenced this pull request Nov 15, 2026
…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.
@morluto morluto added area: mcp MCP server, transport, and tool registration performance Performance regressions, scaling limits, and bounded-resource work labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: mcp MCP server, transport, and tool registration performance Performance regressions, scaling limits, and bounded-resource work

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant