Repository navigation
perf: cut the SDK's repeated schema and compliance work in tests, cold starts and short-lived processes - #3750
Conversation
registerExternalSchemaRoot, withExternalSchemaRoot and withServedReleaseSchemaRoots walked the root two or three times per call and fully loaded every document (JSON.parse plus the reporting-dimension visit) to read its top-level $id and $schema. A 1,620-file, 148 MB release took about 890 ms of CPU per call. Each call now reads every document once through a per-call map, without the reporting-dimension rewrite, which never touches top-level $id or $schema. It also keeps what it read from on-disk documents in a per-file cache shared by the ESM and CommonJS builds. An entry is reused only while the file's inode, size, mtime and ctime are unchanged and older than 3 s, so a quick same-size rewrite is always re-read. Archive-backed bundled entries still go through loadJson and are never cached, so the archive cache that other readers see is unchanged. Measured on one adcp release root (single process, CPU): first check ~890 -> ~380 ms; repeat check of an unchanged root ~800 -> ~17 ms; the CommonJS registration after the ESM one ~850 -> ~27 ms. Results, thrown errors and messages match the stock loader on 101 (version, root) cases, fresh and settled, including null, unparseable, latest/index.json, bundled-only and archive-only roots and file rewrites.
The code.process diagnostic hook runs schemaPathLiterals over every function Ajv generates, which is megabytes of source for one bundled response schema. It tested each character with a one-character RegExp and, at every '/', matched two regular expressions against the whole source prefix. It now compares char codes, decodes a string literal only when it can spell the schemaPath key, and looks back from the '/' for the .replace( call and the data/dataN operand instead of re-matching the prefix. The accepted code units are exactly the RegExp classes they replace (\s, [A-Za-z_$], [\w$]). Over every validator of the four packaged releases (22,589 generated functions, 96.6 MB), process() output is identical and its CPU drops from ~1,800 to ~430 ms; that is about a fifth of the CPU of compiling a bundled response validator.
identity-3.3/trust.ts built an Ajv instance and added the 24 draft identity schemas at module scope. Every package entry point reaches that module, so importing @adcp/sdk, /server, /testing, /client, /compliance and three more entry points did 49 Ajv calls, including a meta-schema check of each schema, before anything was validated (about 45 ms of CPU for the main entry). The schemas are now registered by the first validateIdentity33Schema call; results are unchanged. A guard test requires every CommonJS target in the exports map in one child process and fails if any import calls Ajv's addSchema, compile or validateSchema, with a meta-test that an eager fixture is counted and a deferred one is not.
…or arms createAdcpServer computed the Error-arm inventory of its AdCP version and never read it: two-layer emission looks the inventory up again per request. The scan decompresses the packaged bundle and expands every response schema, about 1.8 s of a cold first construction on a loaded 40-core box. Removing the dead call leaves construction reading no schema document. The new test builds a server against a fresh raw schema root and records every read under it; before this change it saw the manifest, the bundled tree and both response files.
…se carries an error Every request built the Error-arm inventory of its release up front: the whole bundle listed and every response schema expanded once per loader generation, which each schema-root registration bumps. Only the failure path reads it. getErrorArmDescriptor(tool, version) now reads that tool's response schema alone, once per (bundle key, root, generation), and two-layer emission calls it only after it finds an error layer, so a success response reads no schema. Resolution is unchanged: a manifest must declare the tool, and when a bundle ships two response files for one name (list_creative_formats) the last one with an Error arm wins. getToolsWithErrorArm stays for audits and is built from the same per-tool lookups and cache. Tests: construction, a success call and a failing call record their reads on a fresh raw root; the descriptors of every tool in the packaged 3.0, 3.1, 3.2 and 3.3.0-rc.0 bundles equal a fixture taken from the whole-root scan; the external-root scenarios check that the per-tool lookup and the inventory agree.
A storyboard discovery process parsed the compliance storyboards twice: the storyboard index (listAllComplianceStoryboards) and capability resolution (resolveStoryboardsForCapabilities) each loaded every bundle they needed, and each classified every universal file with a full YAML parse. In a candidate-mode discovery child that is 1.38 s of reparse and 0.39 s of reclassification. The index's cache key (resolved compliance dir, release, schema root, hosted alias, index.json stamp and, for custom roots, a stat inventory) now names a compliance scope that holds each bundle's parse and each universal file's classification. The index, capability resolution, resolveBundleOrStoryboard and loadSpecialismDetail read through it and hand out detached copies; a resolved bundle's copies are shared between bundles[] and storyboards as before. A new scope for a custom root still invalidates the signing-vector cache. Resolution and the single-bundle paths now report the resolved compliance directory for a relative root, as the index already did. Tests count YAML reads under a fixture root: resolution after the index, the index after resolution, a relative root and single-bundle resolution reread nothing they already parsed; copies stay detached; a changed custom-root YAML is reparsed.
Combines the six per-commit changesets into .changeset/repeated-validation-work.md (patch).
Every process compiled the bundled-schema validators it used from scratch: compactSchemaForValidation plus Ajv compile, about 0.5-1.1 s per response validator and 17-21 CPU-s of an isolated adcp storyboard process. With ADCP_VALIDATOR_CACHE_DIR set to an absolute directory, getValidator's bundled branch stores each compiled validator as Ajv standalone code and later processes load it instead of compacting and compiling. The stored module carries the code.process diagnostic rewrite (Ajv keeps the code from before the hook, so the loader records the processed body). The key digests the prepared schema, the loader files, the Ajv, ajv-formats and Ajv runtime dependency versions, the Ajv options, the bundle key and the tool. A loaded validator registers its diagnostic origins on the first lookup by compiling its retained schema live once, so issues keep their schemaId and schemaPath. validateRequest and validateResponse read the root $id through a loader accessor, so the success path never builds the schema object. The directory and each entry must belong to the current user with no group or other access; entries are written atomically, verified against the SHA-256 in their header before they run, and opened without following symlinks. Any doubt falls back to the live compile. The variable unset, empty or relative leaves behavior unchanged and never loads the module.
…ered registerExternalSchemaRoot and withExternalSchemaRoot cleared every loader state of the version's aliases on each call. adcp's storyboard runner enters the same candidate root once per storyboard (and the CommonJS loader again), so a single-process tenant recompiled its whole validator set per storyboard: getValidator was 72-79% of those processes' CPU. A root check now also yields a fingerprint: a digest of every document's path and stat key (inode, size, mtime, ctime), defined only when every document is on disk and settled for 3 s, the rule the root-document cache already uses. Entering a root that was already entered for the alias since its states were last cleared, with the same fingerprint, keeps the states and the loader generation. A rewritten or freshly written document, another root for the alias, an archive-backed or `bundled` root, unregister and the reset hook start a fresh epoch exactly as before, so the error-arm and capabilities caches keyed on the generation see every content change. Root checks also memoize version aliases per $id hint: a release root has a few distinct hints across ~1,700 documents, and resolving `latest` throws with a stack trace each time. The validator-cache epoch test rewrites its root before registering it again, so it no longer depends on the files staying unsettled.
…e dir The per-file identity cache made repeat root checks cheap within a process, but each process still parsed every document of every root it checked the first time. An isolated adcp storyboard process checks five release roots (its candidate snapshot, dist/schemas/latest, two retained bundles and the served line), each about 1,700 files and 150 MB: about 9 CPU-s of a 54 CPU-s process, against 380 ms for a single first check of one root. With ADCP_VALIDATOR_CACHE_DIR set, a successful check of a root whose documents are all settled stores one record per document: absolute path, stat key and top-level $id and $schema (or that it does not parse). A later process uses a record only while the document's stat key is unchanged, the rule the in-process cache already applies, and parses every other document. The records are written only when they differ from what is stored, through the same verified, owner-only entry files as cached validators.
Pins that the bundled-validator cache key covers the prepared schema's content rather than its path: after a schema is edited at the same root, path and $id, the next process compiles the edited schema, matches the cache-off result and stores a new entry. Dropping the schema from the key makes the test fail by serving the stored validator.
Each storyboard and discovery process parses the same compliance YAML: in a candidate-mode discovery child, parseStoryboard took 2.1-4.4 s and the universal-file classification another 0.55-0.61 s of YAML parsing. adcp's pre-push matrix repeats this in every child. With ADCP_VALIDATOR_CACHE_DIR set, parseStoryboard and the universal-file classification now parse through parseStoryboardYaml, which stores the parsed document as a data entry in that directory and reads it back in later processes. The key digests the SHA-256 of the document text, the module's code, the yaml package version and the SDK version, so a changed file or parser is a miss. A document with YAML errors or warnings is never stored and goes through parse() every time, so it throws or warns as before. A value is stored only when it survives the JSON round trip (checked with isDeepStrictEqual); objects that YAML aliases share are recorded by path and shared again on read. Every call returns new objects. Storyboard validation still runs on each call. With the variable unset, empty or relative, nothing changes and no cache code loads. Over adcp's dist/compliance/latest (250 storyboards), listAllComplianceStoryboards returns deep-equal storyboards with the same object sharing with the cache cold, warm and off. Tests run listAllComplianceStoryboards in child processes over a fixture root: a second process parses only the document JSON cannot hold (.inf) and keeps aliased objects shared, a changed file is parsed again, without a cache directory nothing is written and no cache code loads, and invalid YAML throws the same error on each call without leaving an entry.
…corded compile releaseDefinesTool asks whether a release defines a framework tool with `getValidator(tool, 'request', version) !== undefined`. tools/list asks this for every framework tool, so one listing compiled every request validator. On a modular schema root the on-disk validator cache does not apply, and a storyboard discovery child spent 3.8-5.9 s there. releaseDefinesTool now calls definesToolRequest, which returns what that rule returns. With ADCP_VALIDATOR_CACHE_DIR set, a modular request schema that compiled is recorded under a key over the root's content (the root-relative path and bytes of every document a modular compile can read, and the index entries), the loader code digest, the ajv, ajv-formats and dependency versions, the V8 and Unicode versions, the bundle key and the tool. Later processes read the record instead of compiling. Only compiles are recorded: a schema that fails compiles in every process, so a transient failure is never reused. A state whose core registration threw records and reads nothing, because Ajv keeps a document it rejects and later compiles in that state then depend on call order. A root that changed between the digest and the first recorded compile stops the state using the cache. Request and response diagnostics read what the loader state compiled (the diagnostic origin map and the registered schema ids). A state whose listing read records compiles those validators before its diagnostics are read, through getRegisteredSchemaIds and the diagnostic origin lookups, against that state. The origin map depends only on the set of compiled validators, so validation issues equal the uncached ones. The compile cost moves to the first validation failure in such a state. Bundled request schemas, and every schema with the cache off, compile as before. On the five shipped roots (3.0, 3.1, 3.2, 3.3.0-beta.6 and adcp's dist/schemas/latest), tools/list (names, order, _meta) is unchanged with the cache off, cold and warm, and so are the diagnostics of 12,187 invalid one-property requests across every request tool. A warm listing of the latest root took 37 ms (cache off: 419 ms; before this change: 384 ms). The tests run tools/list and tools/call in child processes on a modular fixture root: - a schema that does not compile is hidden with the cache off, cold and warm; - a byte copy of a root hits; - each of these misses: a changed referenced document, an invalid document that no tool refs, and a seller whose first compile differs; - request and response diagnostics after a listing equal the cache-off ones.
Combines the five per-commit changesets into .changeset/cross-process-caches.md (patch).
There was a problem hiding this comment.
Ladon verdict: Approve
Approve — pure performance/caching work across 23 files with no wire-shape changes.
What I checked:
- No critical/high/medium findings from the reviewer (rows 1, 4–6 do not fire).
gated_paths: false→ row 2 does not apply despitereview_decision: REVIEW_REQUIRED.high_risk: false, no deletions → rows 3, 5 do not apply.- No no-auto-approve team match → row 7 does not apply.
- Zero medium findings → row 8 does not apply.
- Falls through to row 9 → approve.
Substance verified by reviewer: enrichErrorTwoLayer keeps descriptor reads behind the !envValid && !payloadValid early return, so success responses are unchanged (witness-not-translator preserved). Schema-loader epoch/fingerprint logic is ctime-anchored, preventing stale validator reuse under mtime preservation. validator-cache code-eval is fail-closed (O_NOFOLLOW + fstat owner/mode + SHA-256, atomic rename, failures fall to live compile). YAML cache round-trips through isDeepStrictEqual. Changesets present for the touched src/lib/** paths.
Two Low notes only (opt-in cache under a patch changeset — off-by-default so arguably fine; an imprecise comment matching pre-PR behavior). Lows do not block.
…r cache 17.0.0-beta.32 carries adcontextprotocol/adcp-client#3750 and nothing else: compiled validators and parsed inputs kept across schema-root re-entries and, with ADCP_VALIDATOR_CACHE_DIR set, across processes; schema and compliance work done once. This branch already sets ADCP_VALIDATOR_CACHE_DIR for local storyboard runs and unit suites; beta.31 ignored it. - package.json / package-lock.json: 17.0.0-beta.31 -> 17.0.0-beta.32. The 3,631 bundled schema files are byte-identical to beta.31's. - Choose your SDK, Versions and the creative33 sandbox note name the installed SDK (tests/sdk-runtime-compat requires it). - scripts/sdk-response-conformance: the TypeScript capture re-run on beta.32 matches the recorded baseline apart from the SDK version (125 cases dispatched, 124 schema-valid, the same catalog:list_products finding), so known-findings.json and the README record beta.32. - .changeset/sdk-17-beta-32-docs.md (patch). tests/addie/compliance-authored-tool-gates.test.ts, run alone: 80 s on beta.31 (load 110), 8.3 s on beta.32 (load 90); each runStoryboard call no longer rebuilds the schema root's validators.
The SDK stops repeating schema and compliance work that a test runner, a storyboard runner or a freshly started server pays for. In-process, schema-root checks read each document once, Ajv's diagnostic hook scans generated code by character code, draft identity schemas register on first use, servers are built without scanning the schema root, and each compliance bundle is parsed once per scope. Across processes, and only when
ADCP_VALIDATOR_CACHE_DIRis set, compiled bundled validators, schema-root identities, parsed storyboard YAML and tools/list compile records are stored on disk under keys that cover every input, so only the first process pays for them. In adcp's storyboard runs a warm isolated storyboard process drops from 53.7 to 27.9 profile CPU-s, and single-process tenants use 79-86% less CPU.Where the savings land: tests, cold starts and short-lived processes (storyboard runners, test workers and discovery children that start, compile and exit). A long-running server compiles each validator once anyway: in a production-configuration benchmark, per-request server CPU was unchanged within noise (for example
get_products32.3 against 32.8 ms per request). This PR claims no production request gain.Results, thrown errors and their messages, diagnostics, tool lists and loader epochs are unchanged, with the cache off, cold and warm.
adcontextprotocol/adcp#9102 already sets
ADCP_VALIDATOR_CACHE_DIRfor its local storyboard runs and unit suites; a release with these changes turns the caches on there with a version bump. The numbers below come from adcp runs against a local build of exactly this change.What
Twelve commits, one per change, in two parts, plus two changeset commits.
In-process work done once or lazily (no persistent state):
registerExternalSchemaRoot,withExternalSchemaRootandwithServedReleaseSchemaRootswalked and fully loaded every document two or three times per call to read the top-level$idand$schema. They now read each document once per call, and reuse what they read from an unchanged on-disk document (same inode, size, mtime and ctime, last changed more than 3 s ago) across calls and across the ESM and CommonJS builds. Archive-backed bundled entries are read as before./; it now compares character codes and looks back from the/. Output is identical.@adcp/sdk,@adcp/sdk/serveror@adcp/sdk/testingbuilt an Ajv instance and checked each schema against the meta-schema. Registration now happens on the first identity validation.createAdcpServercomputed an Error-arm inventory it never used; construction now reads no schema document.getErrorArmDescriptor(tool, version)reads one tool's response schema, once per bundle key, root and generation, and two-layer error emission calls it only after it finds an error layer.getToolsWithErrorArmstays and is built from the same lookups.resolveBundleOrStoryboardandloadSpecialismDetailnow share one parse per bundle and one classification per universal file, keyed like the index cache, and return detached copies.Caches that persist across processes (opt-in), and root re-entry:
ADCP_VALIDATOR_CACHE_DIRset to an absolute directory, the bundled branch ofgetValidatorstores each compiled validator as Ajv standalone code, and later processes load it. A loaded validator registers its diagnostic origins on first lookup, so issues keep theirschemaIdandschemaPath.$idand$schema.parseStoryboardand the universal-file classification).releaseDefinesToolasks the stock question (getValidator(tool, 'request', version) !== undefined), and a modular request schema that compiled is recorded so later processes skip the compile; a state that read records compiles those validators before its diagnostics are read.How each cache key covers its inputs, and how that's tested
validator-cache.test.js: identical outcomes off, cold and warm for every bundled release; owner and mode, symlink, tampered and truncated entries fall back to the live compile; an in-place schema edit is a miss, and dropping the schema from the key makes that test failschema-root-reentry.test.js: a later process checks a settled root without parsing it; a changed document's record isn't usedyamlversion and the SDK version; documents with YAML errors or warnings are never stored; values must survive the JSON round tripstoryboard-yaml-cache.test.js(child processes): a second process parses only what JSON can't hold and keeps aliased objects shared; a changed file is parsed again; no directory means no writes and no cache code loaded; invalid YAML throws the same error each time without leaving an entryprocess.versions.v8and.unicode, the bundle key and the tool; only successful compiles are recordedserver-tools-list-compile-outcome.test.js(child processes throughcreateAdcpServer): a non-compiling schema is hidden off, cold and warm; a byte copy of a root hits; a changed referenced document, an invalid unreferenced document and a seller whose first compile differs each miss; diagnostics after a listing equal the cache-off onesEvery entry is written atomically, checked against the SHA-256 in its header before use, and opened without following symlinks; the directory and entries must belong to the current user with no group or other access, and any doubt falls back to the live path.
ADCP_VALIDATOR_CACHE_MAX_MBcaps the directory (default 512). With the variable unset, empty or relative, none of this loads.Measured
In-process changes:
createAdcpServerin a cold workerWhere the costs were found: CPU profiles of adcp's server unit suite on the stock SDK charged 94.9 s to schema-root registration over 43 processes (0.85 s per call, 2-4 calls per process), and
identity-3.3/trust.mjscompiled at import in 299 test files. The VM numbers come from adcp's runs consuming local SDK builds on a 40-core VM shared with other work.Caches and re-entry:
adcp storyboard and pre-push runs consuming local SDK builds on a 40-core VM; every per-storyboard result equals the control.
sg-2(profile / rusage CPU-s, wall)sg-2releaseDefinesTool/compileSchemaA cold run pays to store entries (+3.3 CPU-s in a cold isolated process); only the first process per input pays it.
Behavior changes
For a relative compliance root, capability resolution and the single-bundle paths now report the resolved compliance directory, as the index already did.
Otherwise the in-process changes alter no results: validation results, thrown errors and their messages, diagnostics, tool lists and resolved storyboards are unchanged.
New, opt-in:
ADCP_VALIDATOR_CACHE_DIRandADCP_VALIDATOR_CACHE_MAX_MB.Default behavior, no variable set: an unchanged, settled root keeps its compiled validators and loader generation when it's entered again. Anything else (a rewritten or fresh document, another root, an archive-backed root, unregistering) starts a fresh epoch as before.
Validation results, diagnostics, tool lists and loader epochs are the same with the cache off, cold and warm. On adcp's latest root, 12,187 invalid one-property requests give the same issues with the cache off, cold and warm.
Tests and CI
test/lib/schema-root-check-reads.test.jscounts document reads per root check on fresh, settled and rewritten roots, and covers null, unparseable and archive-only roots.schema-diagnostic-origin.test.jsandschema-diagnostic-origin-bundles.test.jsexercise its output.test/lib/identity-3.3-lazy-schemas.test.js(no identity schema registers before the first validation) andtest/lib/import-time-validator-work.test.js(requires every CommonJS export target in one child and fails if any import calls Ajv'saddSchema,compileorvalidateSchema).test/lib/server-error-arm-lazy.test.js(construction reads no schema document; a success call reads none; a failing call reads only its own tool's response schema, once) andtest/fixtures/error-arm-descriptors.json(every tool's descriptor in the packaged 3.0, 3.1, 3.2 and 3.3.0-rc.0 bundles, from the whole-root scan);server-error-arm-external-roots.test.jschecks that the per-tool lookup and the inventory agree.test/lib/compliance-bundle-parse-once.test.jscounts YAML reads under a fixture root.validator-cache.test.js,schema-root-reentry.test.js,storyboard-yaml-cache.test.js,server-tools-list-compile-outcome.test.js; additions toschema-root-check-reads.test.js..changeset/repeated-validation-work.mdand.changeset/cross-process-caches.md(patch), one per part.npm run format:check,npm run lint,npm run lint:boundaries,npm run typecheck,npm run build:libandnpm test(27,763 tests) pass. One earlier fullnpm testrun on a heavily loaded laptop had a file-level failure intest/lib/handler-controlled-flow.test.js; the file passes alone and in the next full run, andmain's full run passes too.