diff --git a/.github/workflows/codspeed.yml b/.github/workflows/codspeed.yml new file mode 100644 index 000000000..f32a68b16 --- /dev/null +++ b/.github/workflows/codspeed.yml @@ -0,0 +1,55 @@ +name: CodSpeed + +on: + push: + branches: [main] + pull_request: + branches: [main] + # Lets CodSpeed replay a run when it needs a baseline. + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + benchmarks: + name: Benchmarks + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write + env: + NODE_SHA: 768315cf7165e9ff9b636844b776488e9d1703fc + steps: + - name: Harden Runner + uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 + with: + egress-policy: audit + + - name: Setup environment + uses: nodejs/web-team/actions/setup-environment@4c0b18db11a8357664683d70ef1f27af08ecc766 + with: + use-version-file: true + pnpm: true + + - name: Checkout Node.js sources + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + repository: nodejs/node + ref: ${{ env.NODE_SHA }} + sparse-checkout: | + doc + lib + . + path: node + + - name: Run benchmarks + uses: CodSpeedHQ/action@af75f77f17a054769abefaa42fe8dc2975469b5f # v5.6.3 + with: + mode: simulation,memory + run: node --run bench diff --git a/.github/workflows/generate.yml b/.github/workflows/generate.yml index e847d1755..359bd4aff 100644 --- a/.github/workflows/generate.yml +++ b/.github/workflows/generate.yml @@ -145,10 +145,7 @@ jobs: - name: Generate ${{ matrix.target }} run: | - /usr/bin/time \ - --output out/benchmark.json \ - --format '{"elapsedSeconds": %e, "userCpuSeconds": %U, "systemCpuSeconds": %S, "maxRssKiB": %M}' \ - node packages/cli/bin/cli.mjs generate \ + node packages/cli/bin/cli.mjs generate \ -t ${{ matrix.target }} \ -i "${{ matrix.input }}" \ -o out \ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 51de2fb14..8b41d24fc 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -20,6 +20,7 @@ Thank you for your interest in contributing to the `doc-kit` project! We welcome - [Best Practices](#best-practices) - [Example Test File](#example-test-file) - [Running Tests](#running-tests) +- [Benchmarks](#benchmarks) - [Code Quality](#code-quality) - [Linting and Formatting](#linting-and-formatting) - [Pre-commit Hooks](#pre-commit-hooks) @@ -336,6 +337,17 @@ node --run test:coverage node --test packages/core/src/utils/__tests__/parser.test.mjs ``` +## Benchmarks + +Generation speed and memory are measured with [CodSpeed](https://codspeed.io) +(`bench/generate.bench.mjs`), on one thread. The workflow checks `nodejs/node` +out at `NODE_SHA` into `./node`, and the suite reads that directory. It runs on +every pull request and reports CPU and memory there. + +```bash +node --run bench +``` + ## Code Quality ### Linting and Formatting diff --git a/bench/generate.bench.mjs b/bench/generate.bench.mjs new file mode 100644 index 000000000..f7972136a --- /dev/null +++ b/bench/generate.bench.mjs @@ -0,0 +1,66 @@ +import { mkdir, rm } from 'node:fs/promises'; +import path from 'node:path'; + +import { withCodSpeed } from '@codspeed/tinybench-plugin'; +import createGenerator from '@doc-kit/core'; +import logger from '@doc-kit/core/logger/index.mjs'; +import { setConfig } from '@doc-kit/core/utils/configuration/index.mjs'; +import { Bench } from 'tinybench'; + +logger.setLogLevel('warn'); + +const node = path.join(import.meta.dirname, '../node'); +const at = (...parts) => path.join(node, ...parts); + +const shared = { + threads: 1, + index: at('doc/api/index.md'), + typeMap: at('doc/type-map.json'), + changelog: at('CHANGELOG.md'), +}; + +const docs = at('doc/api/*.md'); + +const targets = [ + ['json', docs], + ['json-simple', docs], + ['legacy-json', docs], + ['legacy-html', docs], + ['html', docs], + ['llms-txt', docs], + ['orama-db', docs], + ['man-page', at('doc/api/cli.md')], + ['addon-verify', at('doc/api/addons.md')], + ['api-links', at('lib/*.js')], +]; + +const bench = withCodSpeed( + new Bench({ warmup: false, iterations: 1, time: 0, throws: true }) +); + +for (const [name, input] of targets) { + const output = path.join(import.meta.dirname, '../out', name); + let runGenerators; + let config; + + bench.add(name, () => runGenerators(config), { + beforeAll: async () => { + await rm(output, { recursive: true, force: true }); + await mkdir(output, { recursive: true }); + ({ runGenerators } = createGenerator()); + config = await setConfig({ + ...shared, + target: [name], + input: [input], + output, + }); + }, + afterAll: () => rm(output, { recursive: true, force: true }), + }); +} + +await bench.run(); + +if (process.env.CODSPEED_ENV === undefined) { + console.table(bench.table()); +} diff --git a/docs/contributing/comparators.md b/docs/contributing/comparators.md index 3f3679ec6..422268859 100644 --- a/docs/contributing/comparators.md +++ b/docs/contributing/comparators.md @@ -3,8 +3,7 @@ A comparator is a small Node.js script that compares one generator's output on `main` with its output on a pull request and prints a Markdown report. CI collects these reports into a comment on the pull request, so you and the -reviewers can see what a change does to the generated docs, and to generation -time and memory, before it lands. +reviewers can see what a change does to the generated docs before it lands. Comparators live in `scripts/comparators/` and run only in this repository's CI. They are not part of any published package. @@ -28,11 +27,6 @@ Two workflows work together: request (tagged `compared`, so later pushes update it). If every report is empty, it posts nothing. -Each generation runs under `/usr/bin/time`, which writes `out/benchmark.json` -with the elapsed time, user and system CPU time, and peak resident memory. -Comparators read it for their performance section and leave it out of the -output comparison. - Matrix entries without `compare` (at the moment `man-page`, `addon-verify` and `json-simple`) are generated and uploaded, but not compared. @@ -43,11 +37,6 @@ Matrix entries without `compare` (at the moment `man-page`, `addon-verify` and | `file-size` | Files added, removed or changed in size, largest change first, with the net change, in a collapsible table | [`html`](../generators/html.md), [`orama-db`](../generators/orama-db.md), [`llms-txt`](../generators/llms-txt.md), [`legacy-html`](../generators/legacy-html.md) | | `object-assertion` | Files added or removed, and an `assert.deepStrictEqual` diff for each file whose parsed JSON differs, one per file | [`json`](../generators/json.md), [`api-links`](../generators/api-links.md), [`legacy-json`](../generators/legacy-json.md) | -Both end with a **Performance estimate** section: the generation time and peak -memory of each side, read from `benchmark.json`. It comes from a single CI run, -so treat it as a rough signal. It's left out when either side has no -`benchmark.json`. - Keep their limits in mind when you pick one: - `file-size` compares sizes only. An edit that keeps a file's size the same @@ -57,13 +46,12 @@ Keep their limits in mind when you pick one: ## Shared helpers -| Import | From | What it gives you | -| ----------------------------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `BASE`, `HEAD` | `scripts/constants.mjs` | The two build directories: `base/` and `out/` at the repository root (both gitignored), unless the `BASE` and `HEAD` environment variables point elsewhere. | -| `TITLE` | `scripts/constants.mjs` | The report heading, ``## `` Generator``, built from the `GENERATOR` environment variable, which CI sets to the target name. Set the `TITLE` variable to replace it. | -| `BENCHMARK_FILE`, `COMPARISON_FILE` | `scripts/constants.mjs` | The metadata file names, `benchmark.json` and `comparison.txt`. | -| `listOutputFiles(directory)` | `scripts/comparators/files.mjs` | Every file under `directory`, recursively, as sorted relative paths, without the two metadata files. | -| `comparePerformance()` | `scripts/comparators/performance.mjs` | The performance section as Markdown, or an empty string when either side has no `benchmark.json`. It throws if a benchmark value isn't a finite number. | +| Import | From | What it gives you | +| ---------------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `BASE`, `HEAD` | `scripts/constants.mjs` | The two build directories: `base/` and `out/` at the repository root (both gitignored), unless the `BASE` and `HEAD` environment variables point elsewhere. | +| `TITLE` | `scripts/constants.mjs` | The report heading, ``## `` Generator``, built from the `GENERATOR` environment variable, which CI sets to the target name. Set the `TITLE` variable to replace it. | +| `COMPARISON_FILE` | `scripts/constants.mjs` | The report's file name, `comparison.txt`. | +| `listOutputFiles(directory)` | `scripts/comparators/files.mjs` | Every file under `directory`, recursively, as sorted relative paths, without `comparison.txt`. | ## Writing a comparator @@ -71,14 +59,12 @@ A comparator is an ES module in `scripts/comparators/`. Its file name without `.mjs` is the value of the `compare` field in the workflow matrix. It should: - Read the two builds from `BASE` and `HEAD`, listing their files with - `listOutputFiles`, which skips `benchmark.json` and the `comparison.txt` - that the report is being written to. + `listOutputFiles`, which skips the `comparison.txt` that the report is + being written to. - Print Markdown to standard output, starting with `TITLE`, and print nothing when there's nothing to report. - Report differences instead of failing on them. A comparator that exits with an error fails the CI job, so throw only when something is actually broken. -- End with `comparePerformance()`, like the built-in comparators, so the - timing stays visible. ### Create the script @@ -91,7 +77,6 @@ import { join } from 'node:path'; import { BASE, HEAD, TITLE } from '../constants.mjs'; import { listOutputFiles } from './files.mjs'; -import { comparePerformance } from './performance.mjs'; const [baseFiles, headFiles] = await Promise.all( [BASE, HEAD].map(directory => listOutputFiles(directory)) @@ -127,12 +112,6 @@ if (changes.length) { ); } -const performance = await comparePerformance(); - -if (performance) { - sections.push(performance); -} - if (sections.length) { console.log(`${TITLE}\n\n${sections.join('\n\n')}\n`); } @@ -155,9 +134,6 @@ node packages/cli/bin/cli.mjs generate -t man-page -i ../node/doc/api/cli.md -o GENERATOR=man-page node scripts/comparators/changed-files.mjs ``` -Local builds have no `benchmark.json`, so the report has no performance -section. - ### Add a test Comparator tests live in `scripts/__tests__/comparators.test.mjs` and run with diff --git a/package.json b/package.json index 5e7b5cbb9..e3c95c6ed 100644 --- a/package.json +++ b/package.json @@ -17,6 +17,7 @@ "test:ci": "c8 --reporter=lcov node --test --experimental-test-module-mocks \"packages/*/src/**/*.test.mjs\" \"scripts/**/*.test.mjs\" --test-reporter=@reporters/github --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=junit.xml --test-reporter=spec --test-reporter-destination=stdout", "test:update-snapshots": "node --test --experimental-test-module-mocks --test-update-snapshots \"packages/*/src/**/*.test.mjs\" \"scripts/**/*.test.mjs\"", "test:watch": "node --test --experimental-test-module-mocks --watch \"packages/*/src/**/*.test.mjs\" \"scripts/**/*.test.mjs\"", + "bench": "node bench/generate.bench.mjs", "test:e2e": "playwright test", "prepare": "husky || exit 0", "run": "node packages/cli/bin/cli.mjs", @@ -36,6 +37,8 @@ "devDependencies": { "@changesets/changelog-github": "^1.0.1", "@changesets/cli": "^3.0.3", + "@codspeed/tinybench-plugin": "6.1.0", + "@doc-kit/core": "workspace:*", "@node-core/doc-kit": "workspace:*", "@playwright/test": "~1.65.1", "@reporters/github": "~2.1.4", @@ -50,6 +53,7 @@ "lint-staged": "17.6.2", "oxfmt": "0.80.0", "oxlint": "1.95.0", + "tinybench": "6.2.3", "wrangler": "4.168.0" } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 8eb61974a..0c3671e4b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -172,6 +172,12 @@ importers: '@changesets/cli': specifier: ^3.0.3 version: 3.0.3 + '@codspeed/tinybench-plugin': + specifier: 6.1.0 + version: 6.1.0(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2)(tinybench@6.2.3) + '@doc-kit/core': + specifier: workspace:* + version: link:packages/core '@node-core/doc-kit': specifier: workspace:* version: link:packages/node @@ -214,6 +220,9 @@ importers: oxlint: specifier: 1.95.0 version: 1.95.0 + tinybench: + specifier: 6.2.3 + version: 6.2.3 wrangler: specifier: 4.168.0 version: 4.168.0(@types/node@26.6.6) @@ -648,6 +657,14 @@ packages: vitest: optional: true + '@codspeed/core@6.1.1': + resolution: {integrity: sha512-Lz9xqyeoHI2T7QoLjcJGFrKzyOJKzJM8/2kNRiCcMsqeLzntFpMXHj1No4efraWmdAG+6+7DZmKodrjh+9H6ng==} + + '@codspeed/tinybench-plugin@6.1.0': + resolution: {integrity: sha512-R34+lpwSyCll2CpHSFaVDJq7uHWexlUpSq+FheiaI9qzKb5BNN3z/WNGwFPMcEXO5xpUfjg7qepO83aGuwcSyg==} + peerDependencies: + tinybench: '>=4.0.1' + '@cspotcode/source-map-support@0.8.1': resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==} engines: {node: '>=12'} @@ -2197,6 +2214,10 @@ packages: engines: {node: '>=0.4.0'} hasBin: true + agent-base@6.0.2: + resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==} + engines: {node: '>= 6.0.0'} + agentkeepalive@4.6.0: resolution: {integrity: sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==} engines: {node: '>= 8.0.0'} @@ -2233,6 +2254,9 @@ packages: asynckit@0.4.0: resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==} + axios@1.22.0: + resolution: {integrity: sha512-lVasoE0YvI6ep7jo1dAsukB7lV6VO7uqQZv03ylIc4g7Y2Vamnl0Fim+EBPgp24gUPgqbDXRAMvynAW4KK119g==} + bail@2.0.2: resolution: {integrity: sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw==} @@ -2580,6 +2604,15 @@ packages: flatted@3.4.4: resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==} + follow-redirects@1.16.3: + resolution: {integrity: sha512-toOSoqN6d51Wjf1aOFJYcoVv1aND9rj/CwjLU0Vz40oDuSpWDayCeKe4JpL5NL0WdFvoOOCI3BRo69HahjbR1A==} + engines: {node: '>=4.0'} + peerDependencies: + debug: '*' + peerDependenciesMeta: + debug: + optional: true + foreground-child@3.3.1: resolution: {integrity: sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==} engines: {node: '>=14'} @@ -2699,6 +2732,10 @@ packages: html-void-elements@3.0.0: resolution: {integrity: sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==} + https-proxy-agent@5.0.1: + resolution: {integrity: sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==} + engines: {node: '>= 6'} + human-id@4.2.1: resolution: {integrity: sha512-zPGsiS+dWoTZtZ4AtpA9Y+BdSFSNWvnouNlWNoUFyAM6xHOHmdCvqO3k8AIbdamCOv4gUFUVNPf6rJFfc4UiJw==} hasBin: true @@ -3143,6 +3180,10 @@ packages: encoding: optional: true + node-gyp-build@4.8.4: + resolution: {integrity: sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==} + hasBin: true + nth-check@2.1.1: resolution: {integrity: sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==} @@ -3475,6 +3516,10 @@ packages: spdx-license-ids@3.0.23: resolution: {integrity: sha512-CWLcCCH7VLu13TgOH+r8p1O/Znwhqv/dbb6lqWy67G+pT1kHmeD/+V36AVb/vq8QMIQwVShJ6Ssl5FPh0fuSdw==} + stack-trace@1.0.0-pre2: + resolution: {integrity: sha512-2ztBJRek8IVofG9DBJqdy2N5kulaacX30Nz7xmkYF6ale9WBVmIy6mFBchvGX7Vx/MyjBhx+Rcxqrj+dbOnQ6A==} + engines: {node: '>=16'} + stack-utils@2.0.6: resolution: {integrity: sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==} engines: {node: '>=10'} @@ -3523,6 +3568,10 @@ packages: resolution: {integrity: sha512-nt6AMGKW1p/70DF/hGBdJB57B8Tspmbp5gfJ8ilhLnt7kkr2ye7hzD6NVG8GGErk2HWF34igrL2CXmNIkzKqKw==} engines: {node: '>=18'} + tinybench@6.2.3: + resolution: {integrity: sha512-Al01C2JIBnO2CXCAPbpAl6sUiOZHeThGtHYNTa51JRw9PyWOCdr+9Ong05R4qg/Sk3+H645E8ov1h2c58ityNw==} + engines: {node: '>=20.0.0'} + tinyexec@1.3.1: resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} engines: {node: '>=18'} @@ -4004,6 +4053,24 @@ snapshots: dotenv: 16.3.1 undici: 7.30.2 + '@codspeed/core@6.1.1(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2)': + dependencies: + axios: 1.22.0(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) + form-data: 4.0.6 + node-gyp-build: 4.8.4 + stack-trace: 1.0.0-pre2 + transitivePeerDependencies: + - debug + - supports-color + + '@codspeed/tinybench-plugin@6.1.0(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2)(tinybench@6.2.3)': + dependencies: + '@codspeed/core': 6.1.1(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) + tinybench: 6.2.3 + transitivePeerDependencies: + - debug + - supports-color + '@cspotcode/source-map-support@0.8.1': dependencies: '@jridgewell/trace-mapping': 0.3.9 @@ -5309,6 +5376,12 @@ snapshots: acorn@8.19.0: {} + agent-base@6.0.2(supports-color@10.2.2): + dependencies: + debug: 4.4.3(supports-color@10.2.2) + transitivePeerDependencies: + - supports-color + agentkeepalive@4.6.0: dependencies: humanize-ms: 1.2.1 @@ -5343,6 +5416,15 @@ snapshots: asynckit@0.4.0: {} + axios@1.22.0(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2): + dependencies: + follow-redirects: 1.16.3(debug@4.4.3(supports-color@10.2.2)) + form-data: 4.0.6 + https-proxy-agent: 5.0.1(supports-color@10.2.2) + transitivePeerDependencies: + - debug + - supports-color + bail@2.0.2: {} balanced-match@4.0.4: {} @@ -5723,6 +5805,10 @@ snapshots: flatted@3.4.4: {} + follow-redirects@1.16.3(debug@4.4.3(supports-color@10.2.2)): + optionalDependencies: + debug: 4.4.3(supports-color@10.2.2) + foreground-child@3.3.1: dependencies: cross-spawn: 7.1.2 @@ -5932,6 +6018,13 @@ snapshots: html-void-elements@3.0.0: {} + https-proxy-agent@5.0.1(supports-color@10.2.2): + dependencies: + agent-base: 6.0.2(supports-color@10.2.2) + debug: 4.4.3(supports-color@10.2.2) + transitivePeerDependencies: + - supports-color + human-id@4.2.1: {} humanize-ms@1.2.1: @@ -6598,6 +6691,8 @@ snapshots: dependencies: whatwg-url: 5.0.0 + node-gyp-build@4.8.4: {} + nth-check@2.1.1: dependencies: boolbase: 1.0.0 @@ -7021,6 +7116,8 @@ snapshots: spdx-license-ids@3.0.23: {} + stack-trace@1.0.0-pre2: {} + stack-utils@2.0.6: dependencies: escape-string-regexp: 2.0.0 @@ -7071,6 +7168,8 @@ snapshots: throttleit@2.1.0: {} + tinybench@6.2.3: {} + tinyexec@1.3.1: {} tinyglobby@0.2.17: diff --git a/scripts/__tests__/comparators.test.mjs b/scripts/__tests__/comparators.test.mjs index e398ae7da..cd0547aed 100644 --- a/scripts/__tests__/comparators.test.mjs +++ b/scripts/__tests__/comparators.test.mjs @@ -7,15 +7,6 @@ import { test } from 'node:test'; import { fileURLToPath } from 'node:url'; import { promisify } from 'node:util'; -import { comparePerformance } from '../comparators/performance.mjs'; - -const benchmark = { - elapsedSeconds: 2, - userCpuSeconds: 1, - systemCpuSeconds: 0.5, - maxRssKiB: 1024, -}; - const executeFile = promisify(execFile); const comparatorDirectory = fileURLToPath( new URL('../comparators/', import.meta.url) @@ -35,13 +26,6 @@ const createDirectories = async t => { return { base, head }; }; -const writeBenchmark = (directory, value = benchmark) => - writeFile( - path.join(directory, 'benchmark.json'), - JSON.stringify(value), - 'utf8' - ); - const runComparator = async (name, base, head) => { const { stdout } = await executeFile( process.execPath, @@ -54,63 +38,12 @@ const runComparator = async (name, base, head) => { return stdout; }; -test('comparePerformance summarizes benchmark differences', async t => { - const { base, head } = await createDirectories(t); - - await Promise.all([ - writeBenchmark(base), - writeBenchmark(head, { - elapsedSeconds: 3, - userCpuSeconds: 0.75, - systemCpuSeconds: 0.5, - maxRssKiB: 1536, - }), - ]); - - const result = await comparePerformance(base, head); - - assert.match( - result, - /\*\*Generation time:\*\* 50\.0% slower \(2\.00 s → 3\.00 s\)/ - ); - assert.match( - result, - /\*\*Peak memory:\*\* 50\.0% higher \(1\.00 MB → 1\.50 MB\)/ - ); - assert.match(result, /single CI run/); - assert.doesNotMatch(result, /CPU time/); -}); - -test('comparePerformance omits results when an artifact has no benchmark', async t => { - const { base, head } = await createDirectories(t); - - await writeBenchmark(head); - - assert.equal(await comparePerformance(base, head), ''); -}); - -test('comparePerformance rejects invalid benchmark values', async t => { - const { base, head } = await createDirectories(t); - - await Promise.all([ - writeBenchmark(base), - writeBenchmark(head, { ...benchmark, maxRssKiB: undefined }), - ]); - - await assert.rejects( - comparePerformance(base, head), - /Invalid peak memory benchmark value/ - ); -}); - -test('file-size comparator combines output and performance results', async t => { +test('file-size comparator reports output changes', async t => { const { base, head } = await createDirectories(t); await Promise.all([ writeFile(path.join(base, 'result.txt'), 'base', 'utf8'), writeFile(path.join(head, 'result.txt'), 'a larger result', 'utf8'), - writeBenchmark(base), - writeBenchmark(head, { ...benchmark, elapsedSeconds: 3 }), ]); const result = await runComparator('file-size', base, head); @@ -123,26 +56,19 @@ test('file-size comparator combines output and performance results', async t => /\| File \| Main \| PR \| Change \|\n\| --- \| ---: \| ---: \| ---: \|/ ); assert.match(result, /`result\.txt`/); - assert.match(result, /Performance estimate/); - assert.doesNotMatch(result, /benchmark\.json/); }); -test('object comparator treats benchmark data as metadata', async t => { +test('object comparator is silent when output matches', async t => { const { base, head } = await createDirectories(t); await Promise.all([ writeFile(path.join(base, 'result.json'), '{"value":true}', 'utf8'), writeFile(path.join(head, 'result.json'), '{"value":true}', 'utf8'), - writeBenchmark(base), - writeBenchmark(head, { ...benchmark, maxRssKiB: 2048 }), ]); const result = await runComparator('object-assertion', base, head); - assert.equal(result.match(/## `test` Generator/g)?.length, 1); - assert.doesNotMatch(result, /\*\*Output:/); - assert.match(result, /Performance estimate/); - assert.doesNotMatch(result, /benchmark\.json/); + assert.equal(result, ''); }); test('comparators report added and removed output files', async t => { diff --git a/scripts/comparators/file-size.mjs b/scripts/comparators/file-size.mjs index 81e2e8653..b167cb318 100644 --- a/scripts/comparators/file-size.mjs +++ b/scripts/comparators/file-size.mjs @@ -3,7 +3,6 @@ import path from 'node:path'; import { BASE, HEAD, TITLE } from '../constants.mjs'; import { listOutputFiles } from './files.mjs'; -import { comparePerformance } from './performance.mjs'; const UNITS = ['B', 'KB', 'MB', 'GB']; @@ -84,11 +83,6 @@ if (changed.length) { ); } -const performance = await comparePerformance(); -if (performance) { - sections.push(performance); -} - if (sections.length) { console.log(`${TITLE}\n\n${sections.join('\n\n')}\n`); } diff --git a/scripts/comparators/files.mjs b/scripts/comparators/files.mjs index 7e7d1035c..cb67f4246 100644 --- a/scripts/comparators/files.mjs +++ b/scripts/comparators/files.mjs @@ -1,15 +1,13 @@ import { glob } from 'node:fs/promises'; import path from 'node:path'; -import { BENCHMARK_FILE, COMPARISON_FILE } from '../constants.mjs'; - -const METADATA_FILES = new Set([BENCHMARK_FILE, COMPARISON_FILE]); +import { COMPARISON_FILE } from '../constants.mjs'; export const listOutputFiles = async directory => { const entries = glob('**/*', { cwd: directory, withFileTypes: true, - exclude: entry => METADATA_FILES.has(entry.name), + exclude: entry => entry.name === COMPARISON_FILE, }); return (await Array.fromAsync(entries)) diff --git a/scripts/comparators/object-assertion.mjs b/scripts/comparators/object-assertion.mjs index 33408523d..70b77e18f 100644 --- a/scripts/comparators/object-assertion.mjs +++ b/scripts/comparators/object-assertion.mjs @@ -4,7 +4,6 @@ import { join } from 'node:path'; import { BASE, HEAD, TITLE } from '../constants.mjs'; import { listOutputFiles } from './files.mjs'; -import { comparePerformance } from './performance.mjs'; const [baseFiles, headFiles] = await Promise.all( [BASE, HEAD].map(directory => listOutputFiles(directory)) @@ -51,11 +50,6 @@ if (filteredResults.length) { ); } -const performance = await comparePerformance(); -if (performance) { - sections.push(performance); -} - if (sections.length) { console.log(`${TITLE}\n\n${sections.join('\n\n')}\n`); } diff --git a/scripts/comparators/performance.mjs b/scripts/comparators/performance.mjs deleted file mode 100644 index f3c594ee8..000000000 --- a/scripts/comparators/performance.mjs +++ /dev/null @@ -1,108 +0,0 @@ -import { readFile } from 'node:fs/promises'; -import path from 'node:path'; - -import { BASE, BENCHMARK_FILE, HEAD } from '../constants.mjs'; - -const UNITS = ['B', 'KB', 'MB', 'GB']; - -const formatBytes = bytes => { - if (!bytes) { - return '0 B'; - } - - const unit = Math.min( - Math.floor(Math.log(Math.abs(bytes)) / Math.log(1024)), - UNITS.length - 1 - ); - return `${(bytes / Math.pow(1024, unit)).toFixed(2)} ${UNITS[unit]}`; -}; - -const formatSeconds = seconds => - Math.abs(seconds) < 1 - ? `${(seconds * 1_000).toFixed(2)} ms` - : `${seconds.toFixed(2)} s`; - -const formatPercent = (base, diff) => { - if (base === 0) { - return 'n/a'; - } - - return `${Math.abs((diff / base) * 100).toFixed(1)}%`; -}; - -const formatChange = (base, head, { increase, decrease }) => { - const diff = head - base; - - if (diff === 0) { - return 'unchanged'; - } - - return `${formatPercent(base, diff)} ${diff > 0 ? increase : decrease}`; -}; - -const readBenchmark = async directory => { - try { - return JSON.parse( - await readFile(path.join(directory, BENCHMARK_FILE), 'utf8') - ); - } catch (error) { - if (error.code === 'ENOENT') { - return null; - } - - throw error; - } -}; - -const METRICS = [ - { - label: 'Generation time', - value: benchmark => benchmark.elapsedSeconds, - format: formatSeconds, - change: { increase: 'slower', decrease: 'faster' }, - }, - { - label: 'Peak memory', - value: benchmark => benchmark.maxRssKiB * 1024, - format: formatBytes, - change: { increase: 'higher', decrease: 'lower' }, - }, -]; - -/** - * Builds a Markdown comparison of generation performance. - * - * Missing benchmark files are expected while artifacts created before - * performance measurement are still being used as the comparison base. - * - * @param {string} baseDirectory - Base artifact directory - * @param {string} headDirectory - Head artifact directory - * @returns {Promise} Markdown table, or an empty string - */ -export const comparePerformance = async ( - baseDirectory = BASE, - headDirectory = HEAD -) => { - const [base, head] = await Promise.all( - [baseDirectory, headDirectory].map(readBenchmark) - ); - - if (!base || !head) { - return ''; - } - - const rows = METRICS.map(({ label, value, format, change }) => { - const baseValue = value(base); - const headValue = value(head); - - if (!Number.isFinite(baseValue) || !Number.isFinite(headValue)) { - throw new TypeError(`Invalid ${label.toLowerCase()} benchmark value`); - } - - return `- **${label}:** ${formatChange(baseValue, headValue, change)} (${format(baseValue)} → ${format(headValue)})`; - }); - - return ['**Performance estimate** (single CI run)', ...rows].join( - '\n' - ); -}; diff --git a/scripts/constants.mjs b/scripts/constants.mjs index 2c885d6db..2476dd4ab 100644 --- a/scripts/constants.mjs +++ b/scripts/constants.mjs @@ -10,7 +10,6 @@ export const HEAD = export const TITLE = process.env.TITLE || `## \`${process.env.GENERATOR ?? '...'}\` Generator`; -export const BENCHMARK_FILE = 'benchmark.json'; export const COMPARISON_FILE = 'comparison.txt'; // MDN Constants