diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3ba15c7033..55c20df7f2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -354,20 +354,22 @@ jobs: name: api path: scripts/res/apiDocs/ - # Compares the words the compiler allocates on fixed inputs with the base - # branch (scripts/allocBenchmarks.js). Allocation counts don't depend on the - # runner's speed, so this can fail on a growth of 1%. It is not needed by - # ci-ok: a deliberate growth shouldn't block a merge. The report goes to the - # job summary and, for a pull request from a branch of this repository, to - # a comment on it; a fork's pull request gets a token that can't comment. - alloc-benchmarks: + # Compares the words the compiler allocates on fixed inputs, and the + # instructions it executes on some of them, with the base branch + # (scripts/compilerBenchmarks.js). Neither count depends on the runner's + # speed, so this can fail on a growth of 1%. It is not needed by ci-ok: a + # deliberate growth shouldn't block a merge. The report goes to the job + # summary and, for a pull request from a branch of this repository, to a + # comment on it; a fork's pull request gets a token that can't comment. + benchmarks: if: github.event_name == 'pull_request' - runs-on: ubuntu-26.04-arm + # x64, since bsc doesn't run under valgrind on arm64. + runs-on: ubuntu-26.04 permissions: contents: read pull-requests: write env: - # The same build as the linux-arm64 build-compiler job, so that the + # The same build as the first linux-x64 build-compiler job, so that the # OPAM environment and the dune cache are shared. DUNE_PROFILE: static OCAML_COMPILER: ocaml-variants.5.5.2+options,ocaml-option-static @@ -382,23 +384,29 @@ jobs: uses: ./.github/actions/setup-node - name: Test the benchmark script - run: yarn test-alloc-benchmarks + run: yarn test-compiler-benchmarks - name: Setup Linux dependencies uses: ./.github/actions/setup-linux-dependencies + - name: Install valgrind + run: | + sudo apt-get update -qq + sudo apt-get install -y -qq --no-install-recommends valgrind + valgrind --version + - name: Setup OCaml id: setup_ocaml uses: ./.github/actions/setup-ocaml with: compiler: ${{ env.OCAML_COMPILER }} - os: ubuntu-26.04-arm + os: ubuntu-26.04 cache-prefix: opam-env-v9 - name: Compiler build state key id: compiler-build-state-key run: | - echo "value=compiler-build-state-v1-ubuntu-26.04-arm-${{ steps.setup_ocaml.outputs.setup_version }}-$OCAML_COMPILER-${{ hashFiles('*.opam') }}" \ + echo "value=compiler-build-state-v1-ubuntu-26.04-${{ steps.setup_ocaml.outputs.setup_version }}-$OCAML_COMPILER-${{ hashFiles('*.opam') }}" \ | sed 's/,/-/g' >> "$GITHUB_OUTPUT" - name: Restore compiler build state @@ -412,46 +420,73 @@ jobs: _build key: ${{ steps.compiler-build-state-key.outputs.value }} - - name: Build the compiler, runtime and Belt - run: | - opam exec -- dune build --display quiet - node scripts/allocBenchmarks.js prepare . + - name: Build the compiler + run: opam exec -- dune build --display quiet - - name: Build the base branch's compiler, runtime and Belt + - name: Build the base branch's compiler run: | git worktree add --detach "$RUNNER_TEMP/base" HEAD^1 opam exec -- dune build --root "$RUNNER_TEMP/base" --display quiet - node scripts/allocBenchmarks.js prepare "$RUNNER_TEMP/base" - name: Measure and compare - id: compare env: RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} run: | - node scripts/allocBenchmarks.js measure "$RUNNER_TEMP/base" "$RUNNER_TEMP/base.json" - node scripts/allocBenchmarks.js measure . "$RUNNER_TEMP/head.json" + # Both checkouts are measured from the same path, one after the + # other: the paths in the compiler's arguments change its counts a + # little, and the instructions of the runtime and Belt files by up + # to 0.2%. The runtime and Belt are built there too, since the + # replayed builds would otherwise write interfaces that don't + # match those of the files they don't replay yet. + measure() { + sudo mkdir -p /bench + sudo mount --bind "$1" /bench + node scripts/compilerBenchmarks.js prepare /bench + node scripts/compilerBenchmarks.js measure /bench "$2" --instructions + sudo umount /bench + } + measure "$RUNNER_TEMP/base" "$RUNNER_TEMP/base.json" + measure "$GITHUB_WORKSPACE" "$RUNNER_TEMP/head.json" status=0 - node scripts/allocBenchmarks.js compare "$RUNNER_TEMP/base.json" "$RUNNER_TEMP/head.json" \ - --threshold 1 --summary "$RUNNER_TEMP/alloc-summary.md" || status=$? - cat "$RUNNER_TEMP/alloc-summary.md" >> "$GITHUB_STEP_SUMMARY" + report="$RUNNER_TEMP/benchmarks-report.md" + node scripts/compilerBenchmarks.js compare "$RUNNER_TEMP/base.json" "$RUNNER_TEMP/head.json" \ + --threshold 1 --summary "$report" || status=$? + cat "$report" >> "$GITHUB_STEP_SUMMARY" printf '\nPull request %s compared with base %s in [this run](%s).\n' \ "$(git rev-parse --short=9 HEAD^2)" "$(git rev-parse --short=9 HEAD^1)" "$RUN_URL" \ - >> "$RUNNER_TEMP/alloc-summary.md" - echo "summary=$RUNNER_TEMP/alloc-summary.md" >> "$GITHUB_OUTPUT" + >> "$report" exit "$status" + # When a step failed before the comparison, the comment says so instead + # of keeping the report of an earlier commit. + - name: Report a failure to run the benchmarks + if: ${{ !cancelled() }} + env: + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: | + report="$RUNNER_TEMP/benchmarks-report.md" + if [ ! -f "$report" ]; then + { + echo "## ⚠️ Compiler benchmarks" + echo + echo "The benchmarks couldn't run for pull request ${HEAD_SHA:0:9}; [the run]($RUN_URL) shows why." + } > "$report" + cat "$report" >> "$GITHUB_STEP_SUMMARY" + fi + # The pull request's one comment, edited in place on each push, also # when nothing changed, so that it shows the comparison ran. - name: Comment on the pull request if: >- - !cancelled() && steps.compare.outputs.summary != '' && + !cancelled() && github.event.pull_request.head.repo.full_name == github.repository uses: thollander/actions-comment-pull-request@v3 with: pr-number: ${{ github.event.pull_request.number }} - comment-tag: alloc-benchmarks + comment-tag: compiler-benchmarks mode: upsert - file-path: ${{ steps.compare.outputs.summary }} + file-path: ${{ runner.temp }}/benchmarks-report.md dev-playground: needs: diff --git a/changes/instruction-benchmarks.internal.md b/changes/instruction-benchmarks.internal.md new file mode 100644 index 0000000000..1d501cdbfc --- /dev/null +++ b/changes/instruction-benchmarks.internal.md @@ -0,0 +1 @@ +- Count the instructions the compiler executes on some of the CI benchmarks with cachegrind, next to the words it allocates. diff --git a/package.json b/package.json index 72db98cadf..838d53fe40 100644 --- a/package.json +++ b/package.json @@ -52,7 +52,7 @@ "test-build": "node scripts/test.js -build", "test-ocaml": "node scripts/test.js -ounit", "test-release-plan": "node --test scripts/releasePlan.test.js", - "test-alloc-benchmarks": "node --test scripts/allocBenchmarks.test.js", + "test-compiler-benchmarks": "node --test scripts/compilerBenchmarks.test.js", "check": "biome check --no-errors-on-unmatched .", "check:all": "biome check .", "format": "biome check --no-errors-on-unmatched . --fix", diff --git a/scripts/allocBenchmarks.js b/scripts/allocBenchmarks.js deleted file mode 100644 index e3d2d86519..0000000000 --- a/scripts/allocBenchmarks.js +++ /dev/null @@ -1,485 +0,0 @@ -#!/usr/bin/env node - -// @ts-check - -// Allocation benchmarks: compare how much memory the compiler allocates on a -// fixed set of inputs, before and after a change. -// -// Wall-clock and CPU time are too noisy on shared CI runners to alert on, so -// these benchmarks count the words the compiler allocates, which the OCaml -// runtime reports at exit (OCAMLRUNPARAM=v=0x400). The count is the same in -// every run of the same binary on the same input, and changes by a few words -// with the length of the paths involved. The peak heap size is reported too, -// but isn't usable: it depends on when collections happen, and a few more -// words allocated move it by several percent. -// -// Allocation misses slowdowns that don't allocate, such as a scan of a list -// that already exists, but catches most regressions in the parser, the type -// checker and code generation. -// -// node scripts/allocBenchmarks.js prepare -// node scripts/allocBenchmarks.js measure -// node scripts/allocBenchmarks.js compare -// [--threshold ] [--summary ] -// -// `prepare` builds the runtime and Belt of a checkout whose compiler is -// built. `measure` runs the binaries of a prepared checkout: it replays the -// build of every runtime and Belt source file, one file at a time, with the -// arguments `rescript compiler-args` gives for it, compiles a few generated -// inputs that stress parts of the compiler that were superlinear at some -// point, and parses and formats the large files in tests/alloc_benchmarks/data -// (the build never runs the formatter). The generated inputs and the data -// files come from the checkout of this script, so both measurements use the -// same ones. `compare` reports the changes between two measurements as -// Markdown, improvements and regressions alike, and exits with 1 when a count -// grew by more than the threshold. Runtime and Belt files, whose sources the -// two checkouts may not share, are reported but not alerted on when any of -// them differs. - -import { execFileSync, spawnSync } from "node:child_process"; -import { createHash } from "node:crypto"; -import * as fs from "node:fs"; -import * as os from "node:os"; -import * as path from "node:path"; -import { binDir } from "#cli/bins"; - -const repoRoot = path.join(import.meta.dirname, ".."); - -/** The platform binaries' directory, relative to a checkout's root. */ -const relativeBinDir = path.relative(repoRoot, binDir); - -/** Large files to parse and format, from the checkout of this script. */ -const dataDir = path.join(repoRoot, "tests", "alloc_benchmarks", "data"); - -/** The packages whose sources are replayed, with their source directories. */ -const packages = [ - { dir: "packages/@rescript/runtime", sources: "." }, - { dir: "packages/@rescript/belt", sources: "src" }, -]; - -/** - * `inputs` is a hash of everything besides the compiler that the counts - * depend on. - * - * @typedef {{ allocated: number, inputs: string }} Measurement - * @typedef {Record} Results - */ - -/** - * Reads the allocated words that OCAMLRUNPARAM=v=0x400 prints to stderr at - * exit. - * - * @param {string} stderr - * @returns {number | undefined} - */ -export function parseAllocatedWords(stderr) { - const match = /^allocated_words: (\d+)$/m.exec(stderr); - return match ? Number(match[1]) : undefined; -} - -/** - * Runs an OCaml executable and returns the words it allocated. - * - * @param {string} exe - * @param {string[]} args - * @param {string} cwd - */ -function measureRun(exe, args, cwd) { - const result = spawnSync(exe, args, { - cwd, - encoding: "utf8", - maxBuffer: 256 * 1024 * 1024, - env: { ...process.env, OCAMLRUNPARAM: "v=0x400" }, - }); - const allocated = parseAllocatedWords(result.stderr ?? ""); - if (result.status !== 0 || allocated === undefined) { - throw new Error( - `${exe} ${args.join(" ")} failed in ${cwd} (exit ${result.status}):\n${result.stderr}`, - ); - } - return allocated; -} - -/** - * A short hash of the files' names and contents. - * - * @param {string[]} files - */ -function hashFiles(files) { - const hash = createHash("sha256"); - for (const file of files) { - hash.update(path.basename(file)).update("\0"); - hash.update(fs.readFileSync(file)).update("\0"); - } - return hash.digest("hex").slice(0, 16); -} - -/** - * Generated inputs, one for each part of the compiler that was superlinear - * at some point. They are small enough to compile in well under a second. - * - * @type {Record string>} - */ -export const stressInputs = { - // Exhaustiveness and unused-case checks, and the match compiler. - IntSwitch: () => { - const cases = Array.from( - { length: 1500 }, - (_, i) => ` | ${i} => ${i * 7}`, - ); - return `let f = x =>\n switch x {\n${cases.join("\n")}\n | _ => -1\n }\n`; - }, - PolyVariantSwitch: () => { - const tags = Array.from({ length: 400 }, (_, i) => `#Tag${i}`); - const cases = tags.map((tag, i) => ` | ${tag} => ${i}`); - return `type t = [${tags.join(" | ")}]\nlet f = (x: t) =>\n switch x {\n${cases.join("\n")}\n }\n`; - }, - // Pattern variables of a let rec, and the Lambda SCC of its bindings. - LetRec: () => { - const bindings = Array.from( - { length: 2000 }, - (_, i) => - `and f${i} = x => if x <= 0 { 0 } else { f${(i + 1) % 2000}(x - 1) + ${i} }`, - ); - return `let rec start = x => f0(x)\n${bindings.join("\n")}\n`; - }, - // Label disambiguation and record spreads. - Record: () => { - const fields = Array.from({ length: 300 }, (_, i) => `f${i}`); - return [ - `type t = {${fields.map(f => `${f}: int`).join(", ")}}`, - `let r = {${fields.map((f, i) => `${f}: ${i}`).join(", ")}}`, - ...fields.map((f, i) => `let r${i} = {...r, ${f}: r.${f} + 1}`), - "", - ].join("\n"); - }, - // The JavaScript printer's output for nested constructors. - ListLiteral: () => { - const items = Array.from({ length: 3000 }, (_, i) => `${i}`); - return `let l = list{${items.join(", ")}}\n`; - }, - // Inlining of functions whose bodies were inlined already. - InlineChain: () => { - const fns = Array.from( - { length: 300 }, - (_, i) => `let f${i + 1} = x => f${i}(x) + ${i + 1}`, - ); - return `let f0 = x => x\n${fns.join("\n")}\n`; - }, -}; - -/** - * Builds the runtime and Belt of a checkout whose compiler is built, with - * that checkout's build system. A checkout made with `git worktree add` has - * no node_modules; the build system only needs to find @rescript/runtime. - * - * @param {string} checkout - */ -export function prepare(checkout) { - const scope = path.join(checkout, "node_modules", "@rescript"); - const runtimeLink = path.join(scope, "runtime"); - if (!fs.existsSync(runtimeLink)) { - fs.mkdirSync(scope, { recursive: true }); - fs.symlinkSync( - path.join("..", "..", "packages", "@rescript", "runtime"), - runtimeLink, - "junction", - ); - } - const rescript = path.join(checkout, relativeBinDir, "rescript.exe"); - for (const pkg of packages) { - execFileSync(rescript, ["build"], { - cwd: path.join(checkout, pkg.dir), - stdio: "inherit", - }); - } -} - -/** - * @param {string} checkout - * @returns {Results} - */ -export function measure(checkout) { - const bins = path.join(checkout, relativeBinDir); - const bsc = path.join(bins, "bsc.exe"); - const rescript = path.join(bins, "rescript.exe"); - - /** @type {Results} */ - const results = {}; - - const packageSources = packages.flatMap(pkg => { - const sourceDir = path.join(checkout, pkg.dir, pkg.sources); - return fs - .readdirSync(sourceDir) - .filter(file => file.endsWith(".res") || file.endsWith(".resi")) - .sort() - .map(file => ({ pkg, file, sourcePath: path.join(sourceDir, file) })); - }); - // Each file is compiled against the interfaces of the others, so a change - // to any of them can change what compiling it allocates. - const packageInputs = hashFiles(packageSources.map(s => s.sourcePath)); - - for (const { pkg, file, sourcePath } of packageSources) { - const { parser_args, compiler_args } = JSON.parse( - execFileSync(rescript, ["compiler-args", sourcePath], { - encoding: "utf8", - }), - ); - // The build parses into lib/rescript, then compiles the AST there. The - // outputs these runs write are the ones the build wrote already. - const libDir = path.join(checkout, pkg.dir, "lib", "rescript"); - results[`${pkg.dir}/${path.posix.join(pkg.sources, file)}`] = { - allocated: - measureRun(bsc, parser_args, libDir) + - measureRun(bsc, compiler_args, libDir), - inputs: packageInputs, - }; - } - - // The generated inputs and the data files are compiled in a directory of - // their own under relative names, so that no path of the checkout enters - // their counts. - const workDir = fs.mkdtempSync(path.join(os.tmpdir(), "alloc-bench-")); - try { - const runtime = path.join(checkout, "packages", "@rescript", "runtime"); - for (const [name, generate] of Object.entries(stressInputs)) { - const file = path.join(workDir, `${name}.res`); - fs.writeFileSync(file, generate()); - results[`stress/${name}.res`] = { - allocated: measureRun( - bsc, - ["-runtime-path", runtime, "-bs-no-version-header", `${name}.res`], - workDir, - ), - inputs: hashFiles([file]), - }; - } - - for (const name of fs.readdirSync(dataDir).sort()) { - const file = path.join(workDir, name); - fs.copyFileSync(path.join(dataDir, name), file); - const inputs = hashFiles([file]); - results[`parse/${name}`] = { - allocated: measureRun( - bsc, - ["-bs-ast", "-o", `${path.parse(name).name}.ast`, name], - workDir, - ), - inputs, - }; - results[`format/${name}`] = { - allocated: measureRun(bsc, ["-format", name], workDir), - inputs, - }; - } - } finally { - fs.rmSync(workDir, { recursive: true, force: true }); - } - - return results; -} - -/** - * @typedef {{ - * name: string, - * base: number, - * head: number, - * percent: number, - * inputsChanged: boolean, - * }} Change - */ - -/** - * Lists the counts that differ between two measurements, largest relative - * change first, and the benchmarks that only one of them has. - * - * @param {Results} base - * @param {Results} head - * @param {number} threshold percent above which a growth is a regression - */ -export function compareResults(base, head, threshold) { - /** @type {Change[]} */ - const changes = []; - for (const [name, after] of Object.entries(head)) { - const before = base[name]; - if (!before || before.allocated === after.allocated) continue; - const percent = - before.allocated === 0 - ? Infinity - : ((after.allocated - before.allocated) / before.allocated) * 100; - changes.push({ - name, - base: before.allocated, - head: after.allocated, - percent, - inputsChanged: before.inputs !== after.inputs, - }); - } - changes.sort((x, y) => Math.abs(y.percent) - Math.abs(x.percent)); - - const common = Object.keys(head).filter(name => name in base); - /** @param {Results} results */ - const total = results => - common.reduce((sum, name) => sum + results[name].allocated, 0); - - return { - changes, - regressions: changes.filter(c => !c.inputsChanged && c.percent > threshold), - improvements: changes.filter( - c => !c.inputsChanged && c.percent < -threshold, - ), - added: Object.keys(head).filter(name => !(name in base)), - removed: Object.keys(base).filter(name => !(name in head)), - compared: common.length, - total: { base: total(base), head: total(head) }, - }; -} - -/** @param {number} words */ -const formatWords = words => words.toLocaleString("en-US"); - -/** @param {number} percent */ -const formatPercent = percent => - Number.isFinite(percent) - ? `${percent > 0 ? "+" : ""}${percent.toFixed(2)}%` - : "new"; - -/** @param {number} n */ -const allocate = n => - n === 1 ? "1 benchmark allocates" : `${n} benchmarks allocate`; - -/** - * Changes smaller than this are left out of the table: the paths of the two - * checkouts differ in length, which changes each count by a few words. - */ -const minListedPercent = 0.1; - -/** - * @param {ReturnType} comparison - * @param {number} threshold - * @param {number} [visibleRows] the largest changes shown in the table; the - * others are in a collapsed section under it - */ -export function renderSummary(comparison, threshold, visibleRows = 10) { - const { - changes, - regressions, - improvements, - added, - removed, - compared, - total, - } = comparison; - const totalPercent = - total.base === 0 ? 0 : ((total.head - total.base) / total.base) * 100; - // A total that rounds to 0.00% would read as "+0.00%" or "-0.00%". - const totalChange = - Math.abs(totalPercent) < 0.005 ? "±0.00%" : formatPercent(totalPercent); - // The title shows the overall status: a regression outweighs an - // improvement, and changed inputs alone never count as either. - const status = - regressions.length > 0 ? "⚠️" : improvements.length > 0 ? "🎉" : "✅"; - const lines = [ - `## ${status} Allocation benchmarks`, - "", - `Allocated words in total: ${formatWords(total.base)} → ${formatWords(total.head)} (${totalChange}).`, - "", - ]; - if (regressions.length > 0) { - lines.push( - `**⚠️ Regression: ${allocate(regressions.length)} more than ${threshold}% more.**`, - "", - ); - } - if (improvements.length > 0) { - lines.push( - `**🎉 Improvement: ${allocate(improvements.length)} more than ${threshold}% less.**`, - "", - ); - } - const listed = changes.filter(c => Math.abs(c.percent) >= minListedPercent); - if (listed.length === 0) { - lines.push( - compared === 1 - ? `The benchmark didn't change by ${minListedPercent}% or more.` - : `None of the ${compared} benchmarks changed by ${minListedPercent}% or more.`, - ); - } else { - /** @param {Change[]} rows */ - const table = rows => [ - "| Benchmark | Base | Head | Change |", - "| --- | ---: | ---: | ---: |", - ...rows.map(change => { - const note = change.inputsChanged ? " (inputs changed)" : ""; - return `| \`${change.name}\`${note} | ${formatWords(change.base)} | ${formatWords(change.head)} | ${formatPercent(change.percent)} |`; - }), - ]; - lines.push(...table(listed.slice(0, visibleRows))); - // A change that affects every benchmark lists them all; the largest stay - // visible, and the others are folded away rather than left out. - const folded = listed.slice(visibleRows); - if (folded.length > 0) { - lines.push( - "", - `
${folded.length} more ${folded.length === 1 ? "change" : "changes"}`, - "", - ...table(folded), - "", - "
", - ); - } - if (listed.some(c => c.inputsChanged)) { - lines.push( - "", - "(inputs changed): this pull request changes runtime or Belt sources, so these benchmarks compile different code than on the base, and their changes don't count as regressions.", - ); - } - } - if (added.length > 0) lines.push("", `New: ${added.join(", ")}.`); - if (removed.length > 0) lines.push("", `Removed: ${removed.join(", ")}.`); - return `${lines.join("\n")}\n`; -} - -/** @param {string[]} args */ -function main(args) { - const [command, ...rest] = args; - if (command === "prepare" && rest.length === 1) { - prepare(path.resolve(rest[0])); - return 0; - } - if (command === "measure" && rest.length === 2) { - const [checkout, out] = rest; - const results = measure(path.resolve(checkout)); - fs.writeFileSync(out, `${JSON.stringify(results, null, 2)}\n`); - console.log(`Measured ${Object.keys(results).length} benchmarks.`); - return 0; - } - if (command === "compare" && rest.length >= 2) { - const [basePath, headPath, ...options] = rest; - let threshold = 1; - let summaryPath; - for (let i = 0; i < options.length; i += 2) { - if (options[i] === "--threshold") threshold = Number(options[i + 1]); - else if (options[i] === "--summary") summaryPath = options[i + 1]; - else throw new Error(`Unknown option ${options[i]}`); - } - const base = JSON.parse(fs.readFileSync(basePath, "utf8")); - const head = JSON.parse(fs.readFileSync(headPath, "utf8")); - const comparison = compareResults(base, head, threshold); - const summary = renderSummary(comparison, threshold); - console.log(summary); - if (summaryPath) fs.writeFileSync(summaryPath, summary); - return comparison.regressions.length > 0 ? 1 : 0; - } - console.error( - "Usage: allocBenchmarks.js prepare \n" + - " allocBenchmarks.js measure \n" + - " allocBenchmarks.js compare [--threshold ]\n" + - " [--summary ]", - ); - return 2; -} - -if (import.meta.filename === path.resolve(process.argv[1] ?? "")) { - process.exitCode = main(process.argv.slice(2)); -} diff --git a/scripts/compilerBenchmarks.js b/scripts/compilerBenchmarks.js new file mode 100644 index 0000000000..78601fd6f0 --- /dev/null +++ b/scripts/compilerBenchmarks.js @@ -0,0 +1,736 @@ +#!/usr/bin/env node + +// @ts-check + +// Compiler benchmarks: compare how much memory the compiler allocates, and +// how many instructions it executes, on a fixed set of inputs, before and +// after a change. +// +// Wall-clock and CPU time are too noisy on shared CI runners to alert on, so +// these benchmarks count instead: +// +// - the words the compiler allocates, which the OCaml runtime reports at exit +// (OCAMLRUNPARAM=v=0x400). The count is the same in every run of the same +// binary on the same input from the same path; other paths change it by a +// few words. The peak heap size is reported too, but isn't usable: +// it depends on when collections happen, and a few more words allocated +// move it by several percent. +// - the instructions it executes, which cachegrind reports at exit +// (`valgrind --tool=cachegrind --cache-sim=no`), for a subset of the +// benchmarks, since valgrind runs a program 20 to 50 times slower. This +// catches slowdowns that don't allocate, such as a scan of a list that +// already exists. +// +// node scripts/compilerBenchmarks.js prepare +// node scripts/compilerBenchmarks.js measure [--instructions] +// node scripts/compilerBenchmarks.js compare +// [--threshold ] [--summary ] +// +// `prepare` builds the runtime and Belt of a checkout whose compiler is +// built. `measure` runs the binaries of a prepared checkout: it replays the +// build of every runtime and Belt source file, one file at a time, with the +// arguments `rescript compiler-args` gives for it, compiles a few generated +// inputs that stress parts of the compiler that were superlinear at some +// point, and parses and formats the large files in tests/compiler_benchmarks/data +// (the build never runs the formatter). With `--instructions`, the generated +// inputs, the data files and the largest runtime and Belt files run under +// cachegrind. The generated inputs and the data files come from the checkout +// of this script, so both measurements use the same ones. +// +// `compare` reports the changes between two measurements as Markdown, +// improvements and regressions alike, one section per count, and exits with +// 1 when a count grew by more than the threshold. Runtime and Belt files, +// whose sources the two checkouts may not share, are reported but not +// alerted on when any of them differs. + +import { execFileSync, spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { binDir } from "#cli/bins"; + +const repoRoot = path.join(import.meta.dirname, ".."); + +/** The platform binaries' directory, relative to a checkout's root. */ +const relativeBinDir = path.relative(repoRoot, binDir); + +/** Large files to parse and format, from the checkout of this script. */ +const dataDir = path.join(repoRoot, "tests", "compiler_benchmarks", "data"); + +/** The packages whose sources are replayed, with their source directories. */ +const packages = [ + { dir: "packages/@rescript/runtime", sources: "." }, + { dir: "packages/@rescript/belt", sources: "src" }, +]; + +/** + * How many of the largest runtime and Belt sources run under cachegrind. + * They are chosen by size in the checkout of this script, so that both + * measurements choose the same files. + */ +const instructionPackageFiles = 15; + +/** + * The minor heap of the runs under cachegrind, in words. A few words more or + * less allocated, as from paths of different lengths, move the points where + * the garbage collector runs, and with them how much of a major cycle is + * done before the program exits: that changed instruction counts by up to 3% + * between two builds of the same compiler. With a minor heap larger than + * any benchmark allocates (35M words at most), the collector doesn't run, + * and the instructions are the compiler's own; the cost of collecting is in + * the allocated words, which these settings don't change. The heap is + * mapped only as it's used, but OCaml reserves address space for a minor + * heap per possible domain (128 by default), more than valgrind can give, + * so the runs allow only the one domain bsc uses (d=1). + */ +const cachegrindRuntimeParams = "v=0x400,d=1,s=64M"; + +/** + * `inputs` is a hash of everything besides the compiler that the counts + * depend on. `instructions` is only measured for some benchmarks. + * + * @typedef {{ allocated: number, instructions?: number, inputs: string }} Measurement + * @typedef {Record} Results + * @typedef {"allocated" | "instructions"} Metric + */ + +/** + * Reads the allocated words that OCAMLRUNPARAM=v=0x400 prints to stderr at + * exit. + * + * @param {string} stderr + * @returns {number | undefined} + */ +export function parseAllocatedWords(stderr) { + const match = /^allocated_words: (\d+)$/m.exec(stderr); + return match ? Number(match[1]) : undefined; +} + +/** + * Reads the instructions that cachegrind prints to stderr at exit, as in + * `==1234== I refs: 12,345,678`. + * + * @param {string} stderr + * @returns {number | undefined} + */ +export function parseInstructions(stderr) { + const match = /^==\d+== I\s+refs:\s+([\d,]+)\s*$/m.exec(stderr); + return match ? Number(match[1].replaceAll(",", "")) : undefined; +} + +/** + * Runs an OCaml executable and returns the words it allocated and, under + * cachegrind, the instructions it executed. + * + * @param {string} exe + * @param {string[]} args + * @param {string} cwd + * @param {boolean} instructions + * @returns {{ allocated: number, instructions?: number }} + */ +function measureRun(exe, args, cwd, instructions) { + const [command, commandArgs] = instructions + ? [ + "valgrind", + [ + "--tool=cachegrind", + "--cache-sim=no", + "--cachegrind-out-file=/dev/null", + exe, + ...args, + ], + ] + : [exe, args]; + const result = spawnSync(command, commandArgs, { + cwd, + encoding: "utf8", + maxBuffer: 256 * 1024 * 1024, + env: { + ...process.env, + OCAMLRUNPARAM: instructions ? cachegrindRuntimeParams : "v=0x400", + }, + }); + const stderr = result.stderr ?? ""; + const allocated = parseAllocatedWords(stderr); + const executed = instructions ? parseInstructions(stderr) : undefined; + if ( + result.status !== 0 || + allocated === undefined || + (instructions && executed === undefined) + ) { + const reason = result.error + ? result.error.message + : `exit ${result.status}`; + throw new Error( + `${command} ${commandArgs.join(" ")} failed in ${cwd} (${reason}):\n${stderr}`, + ); + } + return executed === undefined + ? { allocated } + : { allocated, instructions: executed }; +} + +/** + * Adds up the counts of the runs of one benchmark. + * + * @param {{ allocated: number, instructions?: number }[]} runs + */ +function sumRuns(runs) { + const allocated = runs.reduce((sum, run) => sum + run.allocated, 0); + if (runs.some(run => run.instructions === undefined)) return { allocated }; + const instructions = runs.reduce( + (sum, run) => sum + (run.instructions ?? 0), + 0, + ); + return { allocated, instructions }; +} + +/** + * A short hash of the files' names and contents. + * + * @param {string[]} files + */ +function hashFiles(files) { + const hash = createHash("sha256"); + for (const file of files) { + hash.update(path.basename(file)).update("\0"); + hash.update(fs.readFileSync(file)).update("\0"); + } + return hash.digest("hex").slice(0, 16); +} + +/** + * Generated inputs, one for each part of the compiler that was superlinear + * at some point. They are small enough to compile in well under a second, + * and each allocates less than the minor heap of the runs under cachegrind + * (see cachegrindRuntimeParams). + * + * @type {Record string>} + */ +export const stressInputs = { + // Exhaustiveness and unused-case checks, and the match compiler. + IntSwitch: () => { + const cases = Array.from( + { length: 1500 }, + (_, i) => ` | ${i} => ${i * 7}`, + ); + return `let f = x =>\n switch x {\n${cases.join("\n")}\n | _ => -1\n }\n`; + }, + PolyVariantSwitch: () => { + const tags = Array.from({ length: 400 }, (_, i) => `#Tag${i}`); + const cases = tags.map((tag, i) => ` | ${tag} => ${i}`); + return `type t = [${tags.join(" | ")}]\nlet f = (x: t) =>\n switch x {\n${cases.join("\n")}\n }\n`; + }, + // Pattern variables of a let rec, and the Lambda SCC of its bindings. + LetRec: () => { + const bindings = Array.from( + { length: 2000 }, + (_, i) => + `and f${i} = x => if x <= 0 { 0 } else { f${(i + 1) % 2000}(x - 1) + ${i} }`, + ); + return `let rec start = x => f0(x)\n${bindings.join("\n")}\n`; + }, + // Label disambiguation and record spreads. + Record: () => { + const fields = Array.from({ length: 300 }, (_, i) => `f${i}`); + return [ + `type t = {${fields.map(f => `${f}: int`).join(", ")}}`, + `let r = {${fields.map((f, i) => `${f}: ${i}`).join(", ")}}`, + ...fields.map((f, i) => `let r${i} = {...r, ${f}: r.${f} + 1}`), + "", + ].join("\n"); + }, + // The JavaScript printer's output for nested constructors. + ListLiteral: () => { + const items = Array.from({ length: 3000 }, (_, i) => `${i}`); + return `let l = list{${items.join(", ")}}\n`; + }, + // Inlining of functions whose bodies were inlined already. + InlineChain: () => { + const fns = Array.from( + { length: 300 }, + (_, i) => `let f${i + 1} = x => f${i}(x) + ${i + 1}`, + ); + return `let f0 = x => x\n${fns.join("\n")}\n`; + }, + // Field access on a large object type: each access instantiates a copy + // of the whole type. Quadratic in the number of fields. + ObjectFields: () => { + const fields = Array.from({ length: 400 }, (_, i) => `f${i}`); + return [ + `let o = {${fields.map((f, i) => `"${f}": ${i}`).join(", ")}}`, + ...fields.map((f, i) => `let a${i} = o["${f}"] + 1`), + "", + ].join("\n"); + }, + // Expansion of type aliases that refer to the previous one, with the + // cycle check of each new definition. Cubic in the length of the chain. + TypeAliasChain: () => { + const length = 60; + const aliases = Array.from( + { length }, + (_, i) => `type t${i + 1}<'a> = t${i}<('a, int)>`, + ); + return `type t0<'a> = option<'a>\n${aliases.join("\n")}\nlet x: t${length} = None\n`; + }, + // Many mutable references updated in one loop. Superlinear in their + // number although the input is linear. + RefsInLoop: () => { + const refs = Array.from({ length: 300 }, (_, i) => `r${i}`); + return [ + "let f = n => {", + ...refs.map((r, i) => ` let ${r} = ref(${i})`), + " for i in 0 to n {", + ...refs.map((r, i) => ` ${r} := ${r}.contents + i * ${i + 1}`), + " }", + ` ${refs.map(r => `${r}.contents`).join(" + ")}`, + "}", + "", + ].join("\n"); + }, + // Closures nested in closures, each using the variables of all outer ones. + NestedClosures: () => { + const depth = 100; + const lines = ["let f = x0 => {"]; + for (let i = 1; i < depth; i++) { + const used = Array.from({ length: i }, (_, j) => `x${j}`).join(" + "); + lines.push(`${" ".repeat(i)}let g${i} = x${i} => {`); + lines.push(`${" ".repeat(i + 1)}let y${i} = ${used} + x${i}`); + } + lines.push(`${" ".repeat(depth)}y${depth - 1}`); + for (let i = depth - 1; i >= 1; i--) { + lines.push(`${" ".repeat(i)}}`); + lines.push(`${" ".repeat(i)}g${i}(${i})`); + } + lines.push("}", ""); + return lines.join("\n"); + }, +}; + +/** + * The runtime and Belt sources of a checkout, by package. + * + * @param {string} checkout + */ +function packageSources(checkout) { + return packages.flatMap(pkg => { + const sourceDir = path.join(checkout, pkg.dir, pkg.sources); + return fs + .readdirSync(sourceDir) + .filter(file => file.endsWith(".res") || file.endsWith(".resi")) + .sort() + .map(file => ({ + pkg, + file, + name: `${pkg.dir}/${path.posix.join(pkg.sources, file)}`, + sourcePath: path.join(sourceDir, file), + })); + }); +} + +/** + * Builds the runtime and Belt of a checkout whose compiler is built, with + * that checkout's build system. A checkout made with `git worktree add` has + * no node_modules; the build system only needs to find @rescript/runtime. + * + * @param {string} checkout + */ +export function prepare(checkout) { + const scope = path.join(checkout, "node_modules", "@rescript"); + const runtimeLink = path.join(scope, "runtime"); + if (!fs.existsSync(runtimeLink)) { + fs.mkdirSync(scope, { recursive: true }); + fs.symlinkSync( + path.join("..", "..", "packages", "@rescript", "runtime"), + runtimeLink, + "junction", + ); + } + const rescript = path.join(checkout, relativeBinDir, "rescript.exe"); + for (const pkg of packages) { + execFileSync(rescript, ["build"], { + cwd: path.join(checkout, pkg.dir), + stdio: "inherit", + }); + } +} + +/** + * @param {string} checkout + * @param {{ instructions: boolean }} options + * @returns {Results} + */ +export function measure(checkout, { instructions }) { + const bins = path.join(checkout, relativeBinDir); + const bsc = path.join(bins, "bsc.exe"); + const rescript = path.join(bins, "rescript.exe"); + + /** @type {Results} */ + const results = {}; + + const sources = packageSources(checkout); + // Each file is compiled against the interfaces of the others, so a change + // to any of them can change what compiling it allocates. + const packageInputs = hashFiles(sources.map(s => s.sourcePath)); + const underCachegrind = new Set( + instructions + ? packageSources(repoRoot) + .map(s => ({ name: s.name, size: fs.statSync(s.sourcePath).size })) + .sort((a, b) => b.size - a.size || a.name.localeCompare(b.name)) + .slice(0, instructionPackageFiles) + .map(s => s.name) + : [], + ); + + // One file at a time: the runs write the outputs of the build again, and + // read the outputs of the files they depend on. + for (const { pkg, name, sourcePath } of sources) { + const { parser_args, compiler_args } = JSON.parse( + execFileSync(rescript, ["compiler-args", sourcePath], { + encoding: "utf8", + }), + ); + // The build parses into lib/rescript, then compiles the AST there. The + // outputs these runs write are the ones the build wrote already. + const libDir = path.join(checkout, pkg.dir, "lib", "rescript"); + const cachegrind = underCachegrind.has(name); + results[name] = { + ...sumRuns([ + measureRun(bsc, parser_args, libDir, cachegrind), + measureRun(bsc, compiler_args, libDir, cachegrind), + ]), + inputs: packageInputs, + }; + } + + // The generated inputs and the data files are compiled in a directory of + // their own under relative names, so that no path of the checkout enters + // their counts. The directory has the same name in every measurement, so + // that two measurements of the same compiler give the same counts; they + // can't run at the same time. + const workDir = path.join(os.tmpdir(), "compiler-bench"); + fs.rmSync(workDir, { recursive: true, force: true }); + fs.mkdirSync(workDir); + try { + const runtime = path.join(checkout, "packages", "@rescript", "runtime"); + for (const [name, generate] of Object.entries(stressInputs)) { + const file = path.join(workDir, `${name}.res`); + fs.writeFileSync(file, generate()); + results[`stress/${name}.res`] = { + ...measureRun( + bsc, + ["-runtime-path", runtime, "-bs-no-version-header", `${name}.res`], + workDir, + instructions, + ), + inputs: hashFiles([file]), + }; + } + + for (const name of fs.readdirSync(dataDir).sort()) { + const file = path.join(workDir, name); + fs.copyFileSync(path.join(dataDir, name), file); + const inputs = hashFiles([file]); + results[`parse/${name}`] = { + ...measureRun( + bsc, + ["-bs-ast", "-o", `${path.parse(name).name}.ast`, name], + workDir, + instructions, + ), + inputs, + }; + results[`format/${name}`] = { + ...measureRun(bsc, ["-format", name], workDir, instructions), + inputs, + }; + } + } finally { + fs.rmSync(workDir, { recursive: true, force: true }); + } + + return results; +} + +/** + * @typedef {{ + * name: string, + * base: number, + * head: number, + * percent: number, + * inputsChanged: boolean, + * }} Change + */ + +/** + * Lists the counts of one metric that differ between two measurements, + * largest relative change first, and the benchmarks that only one of them + * has. Benchmarks without the metric on either side are left out. + * + * @param {Results} base + * @param {Results} head + * @param {number} threshold percent above which a growth is a regression + * @param {Metric} [metric] + */ +export function compareResults(base, head, threshold, metric = "allocated") { + /** @param {Results} results */ + const withMetric = results => + Object.keys(results).filter(name => results[name][metric] !== undefined); + const baseNames = new Set(withMetric(base)); + const headNames = new Set(withMetric(head)); + const common = [...headNames].filter(name => baseNames.has(name)); + + /** @type {Change[]} */ + const changes = []; + for (const name of common) { + const before = /** @type {number} */ (base[name][metric]); + const after = /** @type {number} */ (head[name][metric]); + if (before === after) continue; + changes.push({ + name, + base: before, + head: after, + percent: before === 0 ? Infinity : ((after - before) / before) * 100, + inputsChanged: base[name].inputs !== head[name].inputs, + }); + } + changes.sort((x, y) => Math.abs(y.percent) - Math.abs(x.percent)); + + /** @param {Results} results */ + const total = results => + common.reduce((sum, name) => sum + (results[name][metric] ?? 0), 0); + + return { + metric, + changes, + regressions: changes.filter(c => !c.inputsChanged && c.percent > threshold), + improvements: changes.filter( + c => !c.inputsChanged && c.percent < -threshold, + ), + added: [...headNames].filter(name => !baseNames.has(name)), + removed: [...baseNames].filter(name => !headNames.has(name)), + compared: common.length, + total: { base: total(base), head: total(head) }, + }; +} + +/** @param {number} count */ +const formatCount = count => count.toLocaleString("en-US"); + +/** @param {number} percent */ +const formatPercent = percent => + Number.isFinite(percent) + ? `${percent > 0 ? "+" : ""}${percent.toFixed(2)}%` + : "new"; + +/** + * The words of a section, by metric. + * + * @type {Record string, + * less: (n: number, threshold: number) => string, + * }>} + */ +const metricWords = { + allocated: { + title: "Allocated words", + more: (n, threshold) => + `${n === 1 ? "1 benchmark allocates" : `${n} benchmarks allocate`} more than ${threshold}% more`, + less: (n, threshold) => + `${n === 1 ? "1 benchmark allocates" : `${n} benchmarks allocate`} more than ${threshold}% less`, + }, + instructions: { + title: "Instructions", + more: (n, threshold) => + `${n === 1 ? "1 benchmark executes" : `${n} benchmarks execute`} more than ${threshold}% more instructions`, + less: (n, threshold) => + `${n === 1 ? "1 benchmark executes" : `${n} benchmarks execute`} more than ${threshold}% fewer instructions`, + }, +}; + +/** + * Changes smaller than this are left out of the table. Measured from the same + * path, two builds of the same compiler give the same counts, so a change + * this small is real, but too small to matter for a pull request. + */ +const minListedPercent = 0.1; + +/** + * The status of comparisons: a regression outweighs an improvement, and + * changed inputs alone never count as either. + * + * @param {ReturnType[]} comparisons + */ +const statusOf = comparisons => + comparisons.some(c => c.regressions.length > 0) + ? "⚠️" + : comparisons.some(c => c.improvements.length > 0) + ? "🎉" + : "✅"; + +/** + * @param {ReturnType} comparison + * @param {number} threshold + * @param {number} visibleRows + */ +function renderSection(comparison, threshold, visibleRows) { + const { + metric, + changes, + regressions, + improvements, + added, + removed, + compared, + total, + } = comparison; + const words = metricWords[metric]; + const totalPercent = + total.base === 0 ? 0 : ((total.head - total.base) / total.base) * 100; + // A total that rounds to 0.00% would read as "+0.00%" or "-0.00%". + const totalChange = + Math.abs(totalPercent) < 0.005 ? "±0.00%" : formatPercent(totalPercent); + const lines = [ + `### ${words.title}`, + "", + `In total: ${formatCount(total.base)} → ${formatCount(total.head)} (${totalChange}).`, + "", + ]; + if (regressions.length > 0) { + lines.push( + `**⚠️ Regression: ${words.more(regressions.length, threshold)}.**`, + "", + ); + } + if (improvements.length > 0) { + lines.push( + `**🎉 Improvement: ${words.less(improvements.length, threshold)}.**`, + "", + ); + } + const listed = changes.filter(c => Math.abs(c.percent) >= minListedPercent); + if (listed.length === 0) { + lines.push( + compared === 1 + ? `The benchmark didn't change by ${minListedPercent}% or more.` + : `None of the ${compared} benchmarks changed by ${minListedPercent}% or more.`, + ); + } else { + /** @param {Change[]} rows */ + const table = rows => [ + "| Benchmark | Base | Head | Change |", + "| --- | ---: | ---: | ---: |", + ...rows.map(change => { + const note = change.inputsChanged ? " (inputs changed)" : ""; + return `| \`${change.name}\`${note} | ${formatCount(change.base)} | ${formatCount(change.head)} | ${formatPercent(change.percent)} |`; + }), + ]; + lines.push(...table(listed.slice(0, visibleRows))); + // A change that affects every benchmark lists them all; the largest stay + // visible, and the others are folded away rather than left out. + const folded = listed.slice(visibleRows); + if (folded.length > 0) { + lines.push( + "", + `
${folded.length} more ${folded.length === 1 ? "change" : "changes"}`, + "", + ...table(folded), + "", + "
", + ); + } + if (listed.some(c => c.inputsChanged)) { + lines.push( + "", + "(inputs changed): this pull request changes runtime or Belt sources, so these benchmarks compile different code than on the base, and their changes don't count as regressions.", + ); + } + } + if (added.length > 0) lines.push("", `New: ${added.join(", ")}.`); + if (removed.length > 0) lines.push("", `Removed: ${removed.join(", ")}.`); + return lines; +} + +/** + * Renders the comparisons as one report, a section for each metric that + * either measurement has. + * + * @param {ReturnType[]} comparisons + * @param {number} threshold + * @param {number} [visibleRows] the largest changes shown in each table; the + * others are in a collapsed section under it + */ +export function renderSummary(comparisons, threshold, visibleRows = 10) { + const shown = comparisons.filter( + c => c.compared > 0 || c.added.length > 0 || c.removed.length > 0, + ); + const lines = [`## ${statusOf(shown)} Compiler benchmarks`]; + for (const comparison of shown) { + lines.push("", ...renderSection(comparison, threshold, visibleRows)); + } + return `${lines.join("\n")}\n`; +} + +/** + * Compares two measurements for every metric. + * + * @param {Results} base + * @param {Results} head + * @param {number} threshold + */ +export function compareAll(base, head, threshold) { + return /** @type {Metric[]} */ (["allocated", "instructions"]).map(metric => + compareResults(base, head, threshold, metric), + ); +} + +/** @param {string[]} args */ +function main(args) { + const [command, ...rest] = args; + if (command === "prepare" && rest.length === 1) { + prepare(path.resolve(rest[0])); + return 0; + } + if ( + command === "measure" && + (rest.length === 2 || (rest.length === 3 && rest[2] === "--instructions")) + ) { + const [checkout, out] = rest; + const results = measure(path.resolve(checkout), { + instructions: rest.length === 3, + }); + fs.writeFileSync(out, `${JSON.stringify(results, null, 2)}\n`); + console.log(`Measured ${Object.keys(results).length} benchmarks.`); + return 0; + } + if (command === "compare" && rest.length >= 2) { + const [basePath, headPath, ...options] = rest; + let threshold = 1; + let summaryPath; + for (let i = 0; i < options.length; i += 2) { + if (options[i] === "--threshold") threshold = Number(options[i + 1]); + else if (options[i] === "--summary") summaryPath = options[i + 1]; + else throw new Error(`Unknown option ${options[i]}`); + } + const base = JSON.parse(fs.readFileSync(basePath, "utf8")); + const head = JSON.parse(fs.readFileSync(headPath, "utf8")); + const comparisons = compareAll(base, head, threshold); + const summary = renderSummary(comparisons, threshold); + console.log(summary); + if (summaryPath) fs.writeFileSync(summaryPath, summary); + return comparisons.some(c => c.regressions.length > 0) ? 1 : 0; + } + console.error( + "Usage: compilerBenchmarks.js prepare \n" + + " compilerBenchmarks.js measure [--instructions]\n" + + " compilerBenchmarks.js compare [--threshold ]\n" + + " [--summary ]", + ); + return 2; +} + +if (import.meta.filename === path.resolve(process.argv[1] ?? "")) { + process.exitCode = main(process.argv.slice(2)); +} diff --git a/scripts/allocBenchmarks.test.js b/scripts/compilerBenchmarks.test.js similarity index 60% rename from scripts/allocBenchmarks.test.js rename to scripts/compilerBenchmarks.test.js index 4d169398f2..222f8fc4c0 100644 --- a/scripts/allocBenchmarks.test.js +++ b/scripts/compilerBenchmarks.test.js @@ -1,11 +1,13 @@ import assert from "node:assert/strict"; import test from "node:test"; import { + compareAll, compareResults, parseAllocatedWords, + parseInstructions, renderSummary, stressInputs, -} from "./allocBenchmarks.js"; +} from "./compilerBenchmarks.js"; const stats = `allocated_words: 628461 minor_words: 593681 @@ -15,11 +17,22 @@ minor_collections: 3 top_heap_words: 208279 `; +const cachegrind = `==4242== Cachegrind, a high-precision tracing profiler +==4242== Command: bsc.exe -format Napkinscript.res +==4242== +==4242== I refs: 1,234,567,890 +`; + test("reads the allocated words from the runtime's statistics", () => { assert.equal(parseAllocatedWords(`Warning 26\n${stats}`), 628461); assert.equal(parseAllocatedWords("minor_words: 1\n"), undefined); }); +test("reads the instructions from cachegrind's report", () => { + assert.equal(parseInstructions(`${stats}${cachegrind}`), 1234567890); + assert.equal(parseInstructions(stats), undefined); +}); + test("alerts on a growth above the threshold only", () => { const base = { a: { allocated: 1000, inputs: "x" }, @@ -62,12 +75,13 @@ test("reports an improvement above the threshold", () => { ["a"], ); assert.deepEqual(comparison.regressions, []); - const summary = renderSummary(comparison, 1); + const summary = renderSummary([comparison], 1); assert.match( summary, /\*\*🎉 Improvement: 1 benchmark allocates more than 1% less\.\*\*/, ); - assert.match(summary, /^## 🎉 Allocation benchmarks$/m); + assert.match(summary, /^## 🎉 Compiler benchmarks$/m); + assert.match(summary, /^### Allocated words$/m); assert.doesNotMatch(summary, /Regression/); assert.match(summary, /\| `a` \| 1,000 \| 800 \| -20\.00% \|/); }); @@ -96,7 +110,7 @@ test("lists benchmarks that only one measurement has", () => { assert.deepEqual(comparison.removed, ["old"]); // Only benchmarks both measurements have count towards the totals. assert.deepEqual(comparison.total, { base: 7, head: 7 }); - const summary = renderSummary(comparison, 1); + const summary = renderSummary([comparison], 1); assert.match(summary, /New: fresh\./); assert.match(summary, /Removed: old\./); assert.match(summary, /^The benchmark didn't change by 0\.1% or more\.$/m); @@ -117,12 +131,12 @@ test("leaves changes below 0.1% out of the table", () => { }, 1, ); - const summary = renderSummary(comparison, 1); + const summary = renderSummary([comparison], 1); assert.match( summary, /\*\*⚠️ Regression: 1 benchmark allocates more than 1% more\.\*\*/, ); - assert.match(summary, /^## ⚠️ Allocation benchmarks$/m); + assert.match(summary, /^## ⚠️ Compiler benchmarks$/m); assert.match(summary, /\| `big` \| 100,000 \| 103,000 \| \+3\.00% \|/); assert.match(summary, /\| `zero` \(inputs changed\) \| 0 \| 10 \| new \|/); assert.match(summary, /^\(inputs changed\): this pull request changes/m); @@ -132,17 +146,19 @@ test("leaves changes below 0.1% out of the table", () => { test("counts several benchmarks in the plural", () => { const summary = renderSummary( - compareResults( - { - a: { allocated: 1000, inputs: "x" }, - b: { allocated: 1000, inputs: "x" }, - }, - { - a: { allocated: 1100, inputs: "x" }, - b: { allocated: 1200, inputs: "x" }, - }, - 1, - ), + [ + compareResults( + { + a: { allocated: 1000, inputs: "x" }, + b: { allocated: 1000, inputs: "x" }, + }, + { + a: { allocated: 1100, inputs: "x" }, + b: { allocated: 1200, inputs: "x" }, + }, + 1, + ), + ], 1, ); assert.match( @@ -155,25 +171,27 @@ test("counts several benchmarks in the plural", () => { test("says how many benchmarks it compared when none changed", () => { const summary = renderSummary( - compareResults( - { - a: { allocated: 100000, inputs: "x" }, - b: { allocated: 5000, inputs: "x" }, - }, - { - // A path-length difference only. - a: { allocated: 100030, inputs: "x" }, - b: { allocated: 5000, inputs: "x" }, - }, - 1, - ), + [ + compareResults( + { + a: { allocated: 100000, inputs: "x" }, + b: { allocated: 5000, inputs: "x" }, + }, + { + // A path-length difference only. + a: { allocated: 100030, inputs: "x" }, + b: { allocated: 5000, inputs: "x" }, + }, + 1, + ), + ], 1, ); assert.match( summary, /^None of the 2 benchmarks changed by 0\.1% or more\.$/m, ); - assert.match(summary, /^## ✅ Allocation benchmarks$/m); + assert.match(summary, /^## ✅ Compiler benchmarks$/m); // The title's symbol is the only one. assert.equal(summary.match(/✅|⚠️|🎉/gu)?.length, 1); assert.doesNotMatch(summary, /\|/); @@ -187,14 +205,14 @@ test("shows the overall status in the title", () => { }; /** @param {Record} head */ const title = head => - renderSummary(compareResults(base, head, 1), 1).split("\n")[0]; + renderSummary([compareResults(base, head, 1)], 1).split("\n")[0]; // A regression outweighs an improvement. assert.equal( title({ a: { allocated: 1100, inputs: "x" }, b: { allocated: 800, inputs: "x" }, }), - "## ⚠️ Allocation benchmarks", + "## ⚠️ Compiler benchmarks", ); // Changed inputs alone are neither. assert.equal( @@ -202,7 +220,69 @@ test("shows the overall status in the title", () => { a: { allocated: 2000, inputs: "y" }, b: { allocated: 1000, inputs: "x" }, }), - "## ✅ Allocation benchmarks", + "## ✅ Compiler benchmarks", + ); +}); + +test("compares instructions where both measurements have them", () => { + const base = { + a: { allocated: 1000, instructions: 50000, inputs: "x" }, + b: { allocated: 1000, inputs: "x" }, + c: { allocated: 1000, instructions: 70000, inputs: "x" }, + }; + const head = { + a: { allocated: 1000, instructions: 60000, inputs: "x" }, + b: { allocated: 1000, instructions: 9, inputs: "x" }, + c: { allocated: 1000, instructions: 70000, inputs: "x" }, + }; + const [allocated, instructions] = compareAll(base, head, 1); + assert.equal(allocated.compared, 3); + assert.deepEqual(allocated.changes, []); + // b has no instructions on the base side. + assert.equal(instructions.compared, 2); + assert.deepEqual(instructions.added, ["b"]); + assert.deepEqual( + instructions.regressions.map(c => c.name), + ["a"], + ); + assert.deepEqual(instructions.total, { base: 120000, head: 130000 }); + + const summary = renderSummary([allocated, instructions], 1); + // A regression in either section shows in the title. + assert.match(summary, /^## ⚠️ Compiler benchmarks$/m); + assert.match(summary, /^### Allocated words$/m); + assert.match(summary, /^### Instructions$/m); + // One symbol for the title and one for the instructions' headline. + assert.equal(summary.match(/✅|⚠️|🎉/gu)?.length, 2); + assert.match( + summary, + /\*\*⚠️ Regression: 1 benchmark executes more than 1% more instructions\.\*\*/, + ); + assert.match(summary, /\| `a` \| 50,000 \| 60,000 \| \+20\.00% \|/); +}); + +test("leaves out the instructions section when nothing measured them", () => { + const results = { a: { allocated: 1000, inputs: "x" } }; + const summary = renderSummary(compareAll(results, results, 1), 1); + assert.match(summary, /^### Allocated words$/m); + assert.doesNotMatch(summary, /Instructions/); +}); + +test("words an improvement in instructions", () => { + const [, instructions] = compareAll( + { + a: { allocated: 1, instructions: 1000, inputs: "x" }, + b: { allocated: 1, instructions: 1000, inputs: "x" }, + }, + { + a: { allocated: 1, instructions: 900, inputs: "x" }, + b: { allocated: 1, instructions: 800, inputs: "x" }, + }, + 1, + ); + assert.match( + renderSummary([instructions], 1), + /\*\*🎉 Improvement: 2 benchmarks execute more than 1% fewer instructions\.\*\*/, ); }); @@ -215,7 +295,7 @@ test("folds all but the 10 largest changes away", () => { base[`b${i}`] = { allocated: 1000, inputs: "x" }; head[`b${i}`] = { allocated: 1010 + i, inputs: "x" }; } - const summary = renderSummary(compareResults(base, head, 1), 1); + const summary = renderSummary([compareResults(base, head, 1)], 1); assert.match( summary, /\*\*⚠️ Regression: 252 benchmarks allocate more than 1% more\.\*\*/, diff --git a/scripts/test_syntax.sh b/scripts/test_syntax.sh index 81a58291e3..e1bc05cb5c 100755 --- a/scripts/test_syntax.sh +++ b/scripts/test_syntax.sh @@ -40,7 +40,7 @@ fi pushd tests -legacyJsReferences=$(find syntax_tests/data alloc_benchmarks/data \( -name "*.res" -o -name "*.resi" \) -exec grep -nHE '(^|[^[:alnum:]_])Js\.' {} + || true) +legacyJsReferences=$(find syntax_tests/data compiler_benchmarks/data \( -name "*.res" -o -name "*.resi" \) -exec grep -nHE '(^|[^[:alnum:]_])Js\.' {} + || true) if [[ $legacyJsReferences != "" ]]; then printf "Legacy Js. references remain in syntax fixtures:\n%s\n" "$legacyJsReferences" exit 1 diff --git a/tests/alloc_benchmarks/data/HeroGraphic.res b/tests/compiler_benchmarks/data/HeroGraphic.res similarity index 100% rename from tests/alloc_benchmarks/data/HeroGraphic.res rename to tests/compiler_benchmarks/data/HeroGraphic.res diff --git a/tests/alloc_benchmarks/data/Napkinscript.res b/tests/compiler_benchmarks/data/Napkinscript.res similarity index 100% rename from tests/alloc_benchmarks/data/Napkinscript.res rename to tests/compiler_benchmarks/data/Napkinscript.res diff --git a/tests/alloc_benchmarks/data/RedBlackTree.res b/tests/compiler_benchmarks/data/RedBlackTree.res similarity index 100% rename from tests/alloc_benchmarks/data/RedBlackTree.res rename to tests/compiler_benchmarks/data/RedBlackTree.res diff --git a/tests/alloc_benchmarks/data/RedBlackTreeNoComments.res b/tests/compiler_benchmarks/data/RedBlackTreeNoComments.res similarity index 100% rename from tests/alloc_benchmarks/data/RedBlackTreeNoComments.res rename to tests/compiler_benchmarks/data/RedBlackTreeNoComments.res