Skip to content

perf(resolver): skip Schema Objects in OpenAPI 3.1 - #4332

Open
jochenberger wants to merge 1 commit into
swagger-api:mainfrom
jochenberger:improve-3.1-perf
Open

jochenberger wants to merge 1 commit into
swagger-api:mainfrom
jochenberger:improve-3.1-perf

Conversation

@jochenberger

Copy link
Copy Markdown

Description

normalize() for OpenAPI 3.1 (ApiDOM strategy) merges five normalization plugins into a single visitor and traverses the whole document. This includes every Schema Object subtree, although none of the plugins can find anything there: they only act on OpenApi3_1Element, PathItemElement, OperationElement, ParameterElement and HeaderElement, and none of these element types can occur inside a Schema Object.

This PR passes a key map to the traversal in which SchemaElement has no children, so schemas are no longer walked during normalization. The change is one new constant and one changed line in src/resolver/strategies/openapi-3-1-apidom/normalize.js. It also adds a unit test that pins down the invariant (the document is still normalized, Schema Object contents are left untouched).

Motivation and Context

Resolving OpenAPI 3.1 documents is much slower than resolving 3.0 ones (see #3805 and the issues linked there). Profiling SwaggerClient.resolve() shows that on a schemas-only spec roughly one third of the time is spent in normalize. This PR removes part of that work. It does not fix #3805: 3.1 resolution stays much slower than 3.0 (about 20 ms for the same content in my measurements), which is why this refers to the issue instead of closing it.

Refs #3805

Measured with SwaggerClient.resolve() in Node on synthetic specs. Median of nine steady-state resolves (three fresh processes, runs 2 to 4):

spec before after
441 kB, 190 paths, 237 schemas 3689 ms 2071 ms (-44 %)
217 kB, schemas only 841 ms 454 ms (-46 %)

Environment: swagger-client 3.39.0, @swagger-api/apidom-* 1.16.0, Node v22.23.5, Ubuntu 24.04.5, 1 vCPU (Intel Xeon 2.30GHz).

How Has This Been Tested?

  • New unit test in test/resolver/strategies/openapi-3-1-apidom/normalize/index.js. It passes before and after the change. With a deliberately wrong key map that also skips Path Item children, 7 of the 10 tests in that file fail.
  • Existing unit tests: on v3.39.0, 100 of 101 suites pass (1224 tests passed, 18 skipped, 1 failed). The failing test, http > encodeFormOrQuery > should handle custom array serialization, fails identically on the unmodified v3.39.0 tree. On current main (0890b13) I ran the 3.1 strategy tests only (35 tests passed) and eslint on the changed files.
  • Output equivalence: I compared a SHA-256 hash of JSON.stringify of the resolved spec before and after, on both specs above. The hashes are identical. The 441 kB spec makes every plugin visibly change the output (operationIds are rewritten, path-level parameters are merged into operations, parameter and header examples are copied into their schemas). Key maps that also stop at OperationElement or PathItemElement change the hash, so the check can fail.
  • Node version: the development docs ask for Node >=24.22.0, I ran everything on Node v22.23.5 (engines says >=22). I have not run it on Node 24.
  • Not measured: Swagger UI timing in a browser, and the OpenAPI 3.2 strategy, which has the same visitorOptions: { keyMap, nodeTypeGetter: getNodeType } line in src/resolver/strategies/openapi-3-2-apidom/normalize.js.

One assumption: the change relies on the five plugins never needing to look inside a Schema Object. refractorPluginNormalizeDiscriminatorMapping in apidom-ns-openapi-3-1 does work on schemas, but it is not part of this plugin list. If it is added later, the key map has to be revisited.

Reproduction scripts
node gen-spec.mjs 3.1.0 > syn-31.json            # schemas only
node gen-rich.mjs syn-31.json 190 > rich-31.json  # adds paths, parameters, examples, security
node bench.mjs syn-31.json                        # run in a project with swagger-client installed
node bench.mjs rich-31.json                       # prints times, error count and output hash

gen-spec.mjs:

// Generates a synthetic OpenAPI document (no real API content).
// Usage: node gen-spec.mjs <openapi-version> [schemas=237] [paths=0] > spec.json
//   node gen-spec.mjs 3.1.0 > synthetic-31.json
//   node gen-spec.mjs 3.0.3 > synthetic-30.json
// Output is deterministic (seeded PRNG), minified JSON.

const version = process.argv[2] ?? '3.1.0';
const nSchemas = Number(process.argv[3] ?? 237);
const nPaths = Number(process.argv[4] ?? 0);

let seed = 42;
const rnd = () => {
  seed = (seed * 1664525 + 1013904223) % 4294967296;
  return seed / 4294967296;
};
const pick = (arr) => arr[Math.floor(rnd() * arr.length)];
const int = (a, b) => a + Math.floor(rnd() * (b - a + 1));

const is31 = version.startsWith('3.1');
const names = Array.from({ length: nSchemas }, (_, i) => `Schema${i}Dto`);
const ref = (name) => ({ $ref: `#/components/schemas/${name}` });

// Nullable differs between 3.0 and 3.1; everything else is valid in both.
const nullable = (s) => (is31 ? { oneOf: [s, { type: 'null' }] } : { ...s, nullable: true });

function primitive() {
  return pick([
    { type: 'string', description: 'A text property of this object.' },
    { type: 'string', format: 'uuid' },
    { type: 'string', format: 'date-time' },
    { type: 'string', enum: ['A', 'B', 'C', 'D'] },
    { type: 'string', minLength: 1, maxLength: 255 },
    { type: 'integer', format: 'int32', minimum: 0 },
    { type: 'boolean' },
  ]);
}

// Layered references keep the dereferenced tree bounded:
// leaves (no refs) <- mid (refs to leaves) <- top (refs to mid and leaves).
const nLeaf = Math.floor(nSchemas * 0.6);
const nMid = Math.floor(nSchemas * 0.25);
const layerOf = (idx) => (idx < nLeaf ? 'leaf' : idx < nLeaf + nMid ? 'mid' : 'top');
const leaves = names.slice(0, nLeaf);
const mids = names.slice(nLeaf, nLeaf + nMid);

function property(idx) {
  const layer = layerOf(idx);
  const targets = layer === 'mid' ? leaves : layer === 'top' ? [...mids, ...leaves] : [];
  const r = rnd();
  if (targets.length && r < 0.30) return ref(pick(targets));
  if (targets.length && r < 0.40) return { type: "array", items: ref(pick(targets)) };
  if (targets.length && r < 0.44) return nullable(ref(pick(targets)));
  if (r < 0.50) return { type: 'array', items: primitive() };
  if (r < 0.55) {
    return {
      type: 'object',
      properties: { key: primitive(), value: primitive() },
    };
  }
  return primitive();
}

const schemas = {};
names.forEach((name, idx) => {
  const props = {};
  const count = int(6, 16);
  for (let i = 0; i < count; i++) props[`property${i}`] = property(idx);
  schemas[name] = {
    type: 'object',
    description: `Synthetic schema number ${idx}.`,
    required: Object.keys(props).slice(0, 3),
    properties: props,
  };
});

const paths = {};
for (let i = 0; i < nPaths; i++) {
  const s = names[i % names.length];
  const json = (schema) => ({ content: { 'application/json': { schema } } });
  paths[`/items${i}/{id}`] = {
    parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string', format: 'uuid' } }],
    get: { operationId: `get${i}`, responses: { 200: { description: 'OK', ...json(ref(s)) } } },
    put: {
      operationId: `put${i}`,
      requestBody: json(ref(s)),
      responses: { 200: { description: 'OK', ...json(ref(s)) } },
    },
  };
}

const spec = {
  openapi: version,
  info: { title: 'Synthetic', version: '1' },
  paths,
  components: { schemas },
};
process.stdout.write(JSON.stringify(spec));

gen-rich.mjs:

// Adds paths/operations/parameters/examples/security to the synthetic schema-only spec,
// so that the normalize plugins have real work to do. usage: node gen-rich.mjs in.json nPaths > out.json
import fs from 'node:fs';
const spec = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
const nPaths = Number(process.argv[3] ?? 190);
const names = Object.keys(spec.components.schemas);
const ref = (n) => ({ $ref: `#/components/schemas/${n}` });
const json = (schema) => ({ content: { 'application/json': { schema } } });
spec.components.securitySchemes = { apiKey: { type: 'apiKey', in: 'header', name: 'X-Key' } };
spec.security = [{ apiKey: [] }];
spec.paths = {};
for (let i = 0; i < nPaths; i++) {
  const s = names[(i * 7) % names.length];
  const pathItem = {
    parameters: [
      { name: 'domainId', in: 'path', required: true, schema: { type: 'string', format: 'uuid' }, example: 'abc' },
      { name: 'id', in: 'path', required: true, schema: { type: 'string', format: 'uuid' }, examples: { one: { value: '1' }, two: { value: '2' } } },
    ],
    get: {
      ...(i % 3 ? { operationId: `get-thing-${i}` } : {}),                 // some operationIds missing / odd
      parameters: [
        { name: 'page', in: 'query', schema: { type: 'integer', example: 0 }, example: 1 },
        { name: 'size', in: 'query', schema: { type: 'integer', examples: [0] }, examples: { small: { value: 10 } } },
      ],
      security: [{ apiKey: [] }],
      responses: { 200: { description: 'OK', headers: { 'X-Rate': { schema: { type: 'integer', example: 0 }, example: 5 }, 'X-Total': { schema: ref(s), examples: { e: { value: {} } } } }, ...json(ref(s)) } },
    },
    put: {
      operationId: `Put_Thing ${i}`,
      parameters: [{ name: 'If-Match', in: 'header', schema: { type: 'string' }, example: 'W/"x"' }],
      requestBody: json(ref(s)),
      responses: { 200: { description: 'OK', ...json(ref(s)) } },
    },
  };
  spec.paths[`/domains/{domainId}/things${i}/{id}`] = pathItem;
}
process.stdout.write(JSON.stringify(spec));

bench.mjs:

import fs from 'node:fs';
import crypto from 'node:crypto';
import SwaggerClient from 'swagger-client';
const spec = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
const times = []; let last;
for (let i = 0; i < 4; i++) { const t = performance.now(); last = await SwaggerClient.resolve({ spec }); times.push(Math.round(performance.now() - t)); }
const hash = crypto.createHash('sha256').update(JSON.stringify(last.spec)).digest('hex').slice(0, 12);
console.log(JSON.stringify({ times, errors: last.errors.length, hash }));

Screenshots (if appropriate):

Types of changes

  • No code changes (changes to documentation, CI, metadata, etc)
  • Dependency changes (any modification to dependencies in package.json)
  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)

None of these fits exactly: this is a performance improvement without a behavior change (commit type perf).

Checklist:

  • My code follows the code style of this project.
  • My change requires a change to the documentation.
  • I have updated the documentation accordingly.
  • I have added tests to cover my changes.
  • All new and existing tests passed. (One existing test, http > encodeFormOrQuery, also fails on the unmodified tree, see above.)

 normalization

None of the normalization plugins handles an element type that can occur
inside a Schema Object. They only act on OpenAPI, Path Item, Operation,
Parameter and Header Objects. Traversing into every Schema Object is
wasted work, so normalize() now uses a key map without Schema children.

Refs swagger-api#3805
@jochenberger jochenberger changed the title [PATCH] perf(resolver): skip Schema Objects in OpenAPI 3.1 perf(resolver): skip Schema Objects in OpenAPI 3.1 Dec 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Extensive memory consumption when using OpenAPI 3.1 spec

1 participant