Skip to content

perf(tests): give MCP test clients the shared lazy schema validation - #10960

Merged
morluto merged 12 commits into
mainfrom
perf/test-mcp-shared-schema-validation
Nov 16, 2026
Merged

morluto merged 12 commits into
mainfrom
perf/test-mcp-shared-schema-validation

Conversation

@morluto

@morluto morluto commented Nov 15, 2026 •

Copy link
Copy Markdown
Owner

Summary

Most of the memory in MCP boundary tests goes to compiling output-schema validators. With the SDK's default Ajv options, the MCP SDK client compiles every listed tool's output schema on its first callTool. tests/fixtures/mcpSchemaValidation.ts already compiles lazily and keeps $refs as shared functions, but about 165 test files still built new Client(...) with the SDK default. This PR moves the native MCP files, the process-boundary MCP files, and four shared harnesses onto the fixture. It also shares compiled validators across clients in a worker and adds a counted guard so that default-validation test clients cannot spread.

Problem and expected behavior

Measured on macOS, warm (artifacts built), with peak process-family RSS sampled every 200 ms:

  • Heap sampling of nativeValueTraceCompleteness.test.ts shows 13.2 GiB allocated, 11.2 GiB of it under the client's outputValidator → Ajv compileSchema.
  • Per schema with the SDK default Ajv: inspect_analysis_view (724 KB, 1,106 $defs) takes 1.7–2.6 s to compile and retains about 500 MiB. Through the fixture it takes 0.65 s and retains 16 MiB.
  • The 29 tests/boundary/mcp/*native* files together peaked at 3.7 GiB. This matches the reported 3.5 GiB "native set" peak.

Expected: test clients pay only for the tools they call, and they pay once per worker.

Change and scope

  • Migrated new Client(...) sites to pass createMcpSchemaValidation(): 15 native MCP files, 7 process-boundary files, and the shared enhancedToolsHarness.ts, sessionMcpHarness.ts, tests/fixtures/buildComputerMcp.ts and tests/fixtures/promptOccurrenceCompletion.ts (about 37 dependent test files). androidMappingMcp.test.ts now uses createTestMcp.
  • mcpSchemaValidation.ts adds a worker-wide cache of compiled SDK validators. The cache is keyed by full schema text and holds at most 32 entries, evicting the least recently used. Sharing is safe because a validator call is synchronous and keeps no state between calls. The bound limits how much the shared module graph retains across files in isolate: false workers.
  • scripts/verify/architecture-guards.mjs counts the new Client(...) calls in tests/**/*.ts whose own arguments do not name jsonSchemaValidator, using a counted baseline that can only shrink (test-mcp-client-default-validation). scripts/verify/mcp-client-validation.mjs reads each call from the dependency-free scripts/verify/source-tokens.mjs tokens (CI runs the guards before npm ci) and looks for jsonSchemaValidator as a key of an object-literal argument, so neighbouring clients, comments and strings cannot hide a default one. The baseline holds the remaining copies. generatedToolCatalog.test.ts, which was added on main after this branch, now uses the shared validation.

Not included:

  • The remaining roughly 145 baseline files are left for later slices. Tests that check the SDK's default validator itself (for example outputValidatorReuse, outputSchemaProfile, toolSchemaValidity, advertisedDialect) should stay on the default.
  • The size of the inspect_analysis_view output schema is a production contract question that affects real SDK clients too, so it is reported separately rather than changed here.
  • Test clients in .mjs scripts are not changed.

Contract and boundary impact

  • Semantic owner and earliest changed stage: tests/fixtures/mcpSchemaValidation.ts, which owns test-client output validation; migrated call sites consume it.
  • Contribution scope fit and linked maintainer decision: not applicable (test infrastructure).
  • CLI and MCP/tool-catalog contract: none. Validation uses the same Ajv 2020 + formats + allErrors policy, minus inlineRefs.
  • Provider, bridge, target-format, or platform compatibility: none.
  • Evidence, artifact, provenance, or reconstruction contract: none.
  • Target selection, authority, upstream behavior, and cleanup details: none.
  • Generated metadata, package, or installation impact: none.

Evidence and regression coverage

Before → after, macOS, warm (vitest and build caches populated; cold runs not measured). Peak is process-family RSS; CPU is user time.

Case Peak RSS Wall User CPU
29 tests/boundary/mcp/*native* files 3,765 → 3,053 MiB 39.8 → 25.7 s 67.9 → 43.9 s
nativeValueTraceCompleteness alone 2,116 → 987 MiB 18.3 → 8.5 s 19.2 → 8.3 s
nativeUiFactsMcp alone 1,976 → 999 MiB 10.5 → 8.7 s 11.2 → 8.4 s
nativeInputContracts alone 1,819 → 909 MiB 10.9 → 6.2 s 11.4 → 6.5 s
androidMappingMcp alone (single worker) 1,415 → 742 MiB 10.3 → 11.6 s 10.7 → 10.0 s

The set's peak is still about 3 GiB. With pool: "threads" and isolate: false, two mcp-boundary worker isolates share one process, and each keeps its high-water heap. That remaining cost needs its own investigation.

  • Guard check: restoring nativeUiFactsMcp.test.ts from main makes architecture-guards.mjs fail with "new copies are not allowed … nativeUiFactsMcp.test.ts: 1 (baseline 0)".
  • Remaining proof gaps: Linux CI memory was not measured.

Validation performed

  • node scripts/run-exact-tests.mjs run <56 affected test files> — 56 files / 448 tests passed (303 s wall, 2.5 GiB peak).
  • node scripts/run-exact-tests.mjs run <29 tests/boundary/mcp/*native* files> after the final change — 29 files / 146 tests passed.
  • node scripts/run-exact-tests.mjs run <40 other files using createMcpSchemaValidation> — 38 passed. mcpDoctor and deferredRuntime failed only because .cache/mcp-tool-catalog.json was missing. npm run test:focused -- tests/boundary/mcp/mcpDoctor.test.ts tests/boundary/mcp/deferredRuntime.test.ts then passed: 2 files / 72 tests.
  • node scripts/verify/architecture-guards.mjs — passed.
  • npm run check:fast — passed.

After the rebase onto main and the review fixes (53c949b):

  • npm run test:focused -- tests/boundary/mcp/mcpSchemaValidation.test.ts tests/boundary/filesystem/mcpClientValidationGuard.test.ts tests/boundary/filesystem/keyedFirstMatchGuard.test.ts tests/boundary/mcp/generatedToolCatalog.test.ts: 4 files, 36 tests passed (18 s wall, 1.3 GiB peak). With per-fixture compilation in place of the shared cache, the new cache test fails as expected.
  • node scripts/verify/architecture-guards.mjs, npm run check:fast and npx oxfmt --check on the changed files all passed.

After rebasing onto main at 5c53bca (#10693), head 1dd25fb: the guard now reuses main's test-file list (testFiles filtered to tests/, comments stripped) instead of a second listTestFiles; androidMappingMcp.test.ts keeps main's canonicalOutputSchema import.

  • npm run test:focused -- tests/boundary/filesystem/mcpClientValidationGuard.test.ts tests/boundary/process/androidMappingMcp.test.ts tests/boundary/mcp/mcpSchemaValidation.test.ts: 3 files, 22 tests passed.
  • node scripts/verify/architecture-guards.mjs --shrink-baselines (no change) and npm run check:fast passed; npx oxfmt --check on the changed files passed.

Review fix (866ddd6): closingParen skips string and template literals, so a ) in a client name does not end the call.

  • npm run test:focused -- tests/boundary/filesystem/mcpClientValidationGuard.test.ts tests/boundary/filesystem/keyedFirstMatchGuard.test.ts: 31 tests passed.
  • node scripts/verify/architecture-guards.mjs --shrink-baselines: passed, no baseline change.

Merged main (42bb643). I resolved one conflict in tests/boundary/mcp/binaryDiagnosticsMcp.test.ts: main's registerServiceTools registration combined with this PR's createMcpSchemaValidation() client.

  • npm run check:fast — passed, including the architecture guards.
  • npm run test:focused -- tests/boundary/mcp/binaryDiagnosticsMcp.test.ts tests/boundary/filesystem/mcpClientValidationGuard.test.ts tests/boundary/mcp/mcpSchemaValidation.test.ts — 3 files, 28 tests passed.
  • Gate equivalent run on this head merged into main fdf856a: oxfmt --check ., npm run check:fast and npm run verify:advertised-schemas all passed.

Merged main after #11316 (fc0c31e). The guard registration conflicted with the per-guard baseline loop; this PR's guard is kept ahead of main's loop. Review fix (07249a6): the counter parses the source with @babel/parser and reads the jsonSchemaValidator property from the call's object-literal arguments. Comments, string literals and client names no longer hide a default client. The generated-child-script allowlist entry no longer matches a call, so it was removed.

  • npm run test:focused -- tests/boundary/filesystem/mcpClientValidationGuard.test.ts: 20 tests passed. The 6 new cases fail against the previous counter.
  • node scripts/verify/architecture-guards.mjs --shrink-baselines passed (no baseline change), and so did npm run check:fast.
  • Merged current main (merge 84f5ab4; import-only conflicts in five more test files after refactor(contracts): own CLI command names, catalog identity and schema presentation in contracts #11425), commit written without the pre-commit lint-staged pass so it carries no unrelated autofixes; pre-push hook ran. Resolved by keeping main's changes (shared binding table registration, phaseGate lifecycle harness, src/ports imports) and re-applying createMcpSchemaValidation() to each client; hostRestrictedAvailabilityMcp.test.ts moved to tests/boundary/mcp/ on main and gets the shared validation there, and webRuntimeMcp.test.ts (new on main) migrates its one remaining default client so the guard stays at zero. After the merge: npm run check:fast (guards included) pass; npm run test:focused -- with cutterCancellationMcp, evidenceImportLifecycle, guidanceMcp, progressMcp, hostRestrictedAvailabilityMcp, webRuntimeMcp and mcpClientValidationGuard 46 passed; briefs/local-gate.sh 10960 perf/test-mcp-shared-schema-validation pass.

Merged main at 465796a (head 3e05330). Conflicting MCP tests take main's version (gdbMcpServer, shared binding table) and pass createMcpSchemaValidation() to each client; two clients main added since (analysisSettingsMcp, debuggerExternalMutationLifecycleMcp) take it too. CI Static checks had failed with ERR_MODULE_NOT_FOUND: @babel/parser because the guard step runs before dependency installation; the counter now uses main's tokenizer instead. providerSelectionMcp's snapshot-mismatch test exceeded max-lines-per-function after the merge: its raw-binary entry-point scenario is now a helper, and its three local SHA-256 copies use sha256Hex from src/kernel.

  • npm run test:focused -- tests/boundary/filesystem/mcpClientValidationGuard.test.ts — 20 passed.
  • npm run test:focused -- <5 files: providerSelectionMcp, analyzeFunctionDetail, gdbCloseDisposition, analysisSettingsMcp, batchSourcePublicationRecovery> — 39 passed (13.7 s, 1.2 GB peak).
  • npm run test:focused -- <9 files: cutter/frida/gdb/rizin cancellation and output MCP tests, RizinDebugSessionInferiorStdin, debuggerExternalMutationLifecycleMcp> — 120 passed, 9 skipped (20.8 s, 1.2 GB peak).
  • node scripts/verify/architecture-guards.mjs and pre-push npm run check:fast — passed.
  • CI Test shard 11 failure cliOptionAliases.test.ts also fails on main; fixed separately in fix(cli): describe a contract option whose description sits inside .optional() #11661.

Compatibility, safety, and release

  • Breaking changes or migration steps: none.
  • Real Hopper/Ghidra, browser, or OS coverage: macOS only.
  • Package or release metadata impact: none.
  • 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.

@chatgpt-codex-connector

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

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

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

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-16T02:44:23.895795Z
We couldn’t complete this review. Comment @codex review to try again.
e795d48 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

[Medium impact] The PR appears safe to merge; no blocking issues were found.

Summary

This PR moves MCP test clients onto lazy schema validation and shares compiled validators through a bounded worker cache.

  • MCP tests reuse compiled validators in a bounded worker cache.
  • MCP test clients use the shared lazy schema validator.
  • The architecture checks count test clients that use default validation.

morluto accepted conservative counting of parenthesized, conditional, spread, and nested options. morluto also noted that regex literals remain unsupported by the older closingParen helper.

No new actionable issues or security problems were found. The changes are not already present in the supplied base.

Reviews (12) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..." · Reviewed by Greptile

Comment thread scripts/verify/architecture-guards.mjs Resolved
Comment thread tests/fixtures/mcpSchemaValidation.ts Resolved
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

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.
@morluto
morluto force-pushed the perf/test-mcp-shared-schema-validation branch from 1dd25fb to 632d2ee Compare November 15, 2026 14:25
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@morluto

morluto commented Nov 15, 2026

Copy link
Copy Markdown
Owner Author

@greptileai please review the latest commit: the branch was rebased onto main after #10693, and the findings from the earlier review are addressed in the current head.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

…ion (#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)
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@morluto

morluto commented Nov 15, 2026

Copy link
Copy Markdown
Owner Author

Verification of the remaining-cleanup note ("regex literals are not tokenized; none occur at the counted sites"), run against this branch's tree at f66e2a1.

I parsed every src/**/*.ts and tests/**/*.ts file with the TypeScript 6 parser. For each new Client(...) and each .filter(...) call (4,181 calls, a superset of the counted sites), I compared the end that closingParen finds with the AST call end, and listed the regex literals inside each call.

  • new Client(...): no call has a regex literal in its arguments, and closingParen matches the AST at every call.
  • .filter(...): 48 calls have a regex literal inside. At 47 of them closingParen still matches the AST, because the literal has no quote or parenthesis that misleads the scan. The one mismatch is tests/boundary/mcp/browserScenarioMcp.test.ts:232, where /\(\?<?[=!]|.../u contains \(. That predicate destructures pattern, which is not in the guard's key set (name|type|cmd|command|tag), and the result is not indexed with [0]. So it is not a counted site.

So the claim holds: no counted site has a regex literal that changes the count. The failure mode is real, though, as that uncounted site shows. A future keyed filter(...)[0] with (, ) or a quote inside a regex literal would be measured wrongly. No code change in this PR. Tokenizing regex literals would mean deciding when / starts a regex versus division. That is extra complexity for a case no counted site has, so it is left out unless the maintainer wants it.

# Conflicts:
#	tests/boundary/mcp/binaryDiagnosticsMcp.test.ts
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

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

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

Comment thread scripts/verify/architecture-guards.mjs Resolved
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@morluto
morluto force-pushed the perf/test-mcp-shared-schema-validation branch from 5e22c5a to 5e38086 Compare November 15, 2026 21:25
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@morluto

morluto commented Nov 15, 2026

Copy link
Copy Markdown
Owner Author

@greptileai review — please review the latest commit (merge of current main).

Conflicting MCP test files take main's version (gdbMcpServer and the
shared binding table) and pass createMcpSchemaValidation() to each client.
Two clients main added since (analysisSettingsMcp,
debuggerExternalMutationLifecycleMcp) take it too.

The guard's call reader now tokenizes with scripts/verify/source-tokens.mjs
instead of @babel/parser: CI runs the architecture guards before npm ci, so
the parser import failed Static checks with ERR_MODULE_NOT_FOUND.

providerSelectionMcp: the snapshot-mismatch test exceeded
max-lines-per-function after the client gained its option; its raw-binary
entry-point scenario is now its own helper, and the file's three local
SHA-256 copies use sha256Hex from src/kernel.
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

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

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

…schema-validation

# Conflicts:
#	tests/boundary/mcp/largeToolResult.test.ts
#	tests/boundary/mcp/sessionEvidenceReuseMcp.test.ts
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@morluto
morluto merged commit 858ff73 into main Nov 16, 2026
13 checks passed
@morluto
morluto deleted the perf/test-mcp-shared-schema-validation branch November 16, 2026 02:53
hemv-857 added a commit to hemv-857/rea that referenced this pull request Nov 16, 2026
Follow main's shared MCP test-client validation (morluto#10960): the
architecture guard rejects a default-validating SDK client in tests.
Pass createMcpSchemaValidation through the client, matching the other
MCP boundary suites.

Signed-off-by: Hemang Varshney <[email protected]>
@morluto morluto added area: tests Test suite and verification 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: tests Test suite and verification performance Performance regressions, scaling limits, and bounded-resource work

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant