Optimize Ajv refs for external schema branches#853
Conversation
Fdawgs
left a comment
There was a problem hiding this comment.
Any supporting benchmarks for this optimisation?
There was a problem hiding this comment.
Pull request overview
This pull request optimizes how fast-json-stringify selects the Ajv schema reference used for runtime branch validation in oneOf/anyOf and if schemas, allowing validation to target already-registered external schema refs directly when the branch is a “pure” $ref.
Changes:
- Add
getValidatorSchemaRef()to redirect validator refs from root-relative JSON-pointer paths to external registered$reftargets when safely resolvable. - Use the new validator-ref selection in
buildOneOfandbuildIfThenElse. - Add regression/behavior tests covering bare refs,
$idrefs (absolute and relative), named fragments, JSON-pointer subpaths, and non-redirected cases (inline branches and$refwith sibling keywords).
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
| index.js | Introduces getValidatorSchemaRef() and applies it to Ajv validation calls in oneOf/anyOf and if codegen paths. |
| test/oneof.test.js | Adds targeted tests asserting standalone output uses direct external validator refs for eligible oneOf branches (and preserves behavior for ineligible cases). |
| test/anyof.test.js | Adds a test ensuring anyOf branch validator refs resolve directly to registered external targets. |
| test/if-then-else.test.js | Adds tests ensuring if schema validator refs resolve directly to registered external targets (and are not redirected when $ref has siblings). |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
Added a benchmark covering the affected path: cold Local before/after using the same benchmark workload:
That works out to roughly:
I also ran the full benchmark suite locally after adding the benchmark, and the new case reported: |
Redirect buildOneOf's Ajv ref to a registered ref target when possible.
buildOneOf currently validates oneOf/anyOf branches through location.getSchemaRef(), which points back into the generated root schema even when the branch is only an external ref already registered with Ajv. This lets those branches validate against the exact external ref target instead, so Ajv can use the already-registered schema path rather than resolving through the root document.
The helper is intentionally guarded:
This also applies the same validator-ref selection to if schemas, which use the same runtime validator path.
Verification:
npm run test:unit passed locally with 488 tests and 0 failures. The local run printed Node inspector auto-attach warnings, but exited successfully.