diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c90099d6..36c661c8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -116,6 +116,58 @@ jobs: run: pnpm run test working-directory: ${{ matrix.package.path }} + release-diff: + name: Release diff v18 vs published libpg-query πŸ”¬ + needs: build-wasm + runs-on: ubuntu-latest + steps: + - name: Checkout Repository πŸ“₯ + uses: actions/checkout@v4 + + - name: Setup Node.js 🌐 + uses: actions/setup-node@v4 + with: + node-version: '20.x' + + - name: Setup pnpm πŸ“¦ + uses: pnpm/action-setup@v2 + with: + version: 8.15.1 + + - name: Get pnpm store directory πŸ“ + shell: bash + run: | + echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_ENV + + - name: Setup pnpm cache πŸ—„οΈ + uses: actions/cache@v3 + with: + path: ${{ env.STORE_PATH }} + key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} + restore-keys: | + ${{ runner.os }}-pnpm-store- + + - name: Install Dependencies 🧢 + run: pnpm install + + - name: Download WASM Artifacts πŸ“₯ + uses: actions/download-artifact@v4 + with: + name: wasm-artifacts-v18 + path: versions/18/wasm/ + + - name: Compare with the published release πŸ”¬ + run: pnpm run release-diff --major 18 + + - name: Upload Release Diff Report πŸ“¦ + if: always() + uses: actions/upload-artifact@v4 + with: + name: release-diff-v18 + path: versions/18/.release-diff/report.json + if-no-files-found: ignore + retention-days: 7 + build-parser: name: Build Parser Package πŸ“¦ needs: build-wasm diff --git a/.gitignore b/.gitignore index b920b6e0..b0bbcb5b 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,4 @@ npm-debug.log .claude .openhands/ .DS_Store +versions/*/.release-diff/ diff --git a/README.md b/README.md index 3dcd25af..869d6bb1 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,24 @@ pnpm run test pnpm run clean && pnpm run build && pnpm run test ``` +### Release diff + +CI runs every pgsql-parser kitchen-sink and PL/pgSQL fixture, a set of deep and +large generated inputs, and the PG 18 test suite through the last published +`libpg-query` (`pg18` dist-tag) and the candidate build in `versions/18/wasm/`. +Any output or error that changed fails the job unless +`versions/18/release-diff.allow.json` names it with a reason. + +```bash +pnpm run release-diff --major 18 +``` + +Options: `--baseline 18.1.5` compares against another published version, +`--fixtures ../pgsql-parser` uses a local pgsql-parser checkout instead of +cloning it, and `--skip-tests` compares only the corpus. + +The report is printed and saved to `versions/18/.release-diff/report.json`. + ### Slow recovery checks (local only) Run these after changing the WASM recovery code in `templates/`. Both use the diff --git a/package.json b/package.json index 909d84d4..dd042298 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "copy:templates": "node scripts/copy-templates.js", "test:stress": "node scripts/test-stress.js", "test:mutations": "node scripts/test-mutations.js", + "release-diff": "node scripts/release-diff", "build:parser": "pnpm --filter @pgsql/parser build", "build:parser:lts": "PARSER_BUILD_TYPE=lts pnpm --filter @pgsql/parser build", "build:parser:full": "PARSER_BUILD_TYPE=full pnpm --filter @pgsql/parser build", diff --git a/scripts/release-diff/allowlist.js b/scripts/release-diff/allowlist.js new file mode 100644 index 00000000..f4e5497a --- /dev/null +++ b/scripts/release-diff/allowlist.js @@ -0,0 +1,43 @@ +// versions//release-diff.allow.json: the differences a release intends. +// +// { "allow": [{ +// "id": "kitchen-sink:*:fingerprint", // input:function, `*` matches anything; or a list +// "reason": "why the release changes this", +// "baseline": "18.1.5", // optional: only against this release +// "published": "ok", "candidate": "ok" // optional: `ok`, `pass` or the error message +// "ignoreKeys": ["arg_location"] // optional: outputs equal without these keys +// }] } +// +// An entry only allows what it names: without `published` / `candidate` any +// change to the matched outputs passes, so give them whenever the change is a +// new or lost error, and prefer `ignoreKeys` to allowing a whole output. +const fs = require('node:fs'); + +function globToRegExp(glob) { + return new RegExp('^' + glob.split('*').map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*') + '$', 's'); +} + +function loadAllowlist(file, baselineVersion) { + if (!fs.existsSync(file)) return []; + return (JSON.parse(fs.readFileSync(file, 'utf8')).allow || []) + .filter((entry) => !entry.baseline || entry.baseline === baselineVersion) + .map((entry) => { + if (!entry.id || !entry.reason) throw new Error(`${file}: every entry needs an id and a reason`); + const optional = (glob) => (glob === undefined ? null : globToRegExp(glob)); + return { ...entry, idPatterns: [].concat(entry.id).map(globToRegExp), publishedPattern: optional(entry.published), candidatePattern: optional(entry.candidate), used: 0 }; + }); +} + +const summary = (outcome) => ('ok' in outcome ? 'ok' : outcome.error); + +function allows(entry, diff) { + return entry.idPatterns.some((pattern) => pattern.test(diff.id)) + && (!entry.publishedPattern || entry.publishedPattern.test(summary(diff.baseline))) + && (!entry.candidatePattern || entry.candidatePattern.test(summary(diff.candidate))); +} + +function withoutKeys(json, keys) { + return JSON.stringify(JSON.parse(json), (key, value) => (keys.has(key) ? undefined : value)); +} + +module.exports = { loadAllowlist, allows, withoutKeys }; diff --git a/scripts/release-diff/collect.js b/scripts/release-diff/collect.js new file mode 100644 index 00000000..e0aa7c7e --- /dev/null +++ b/scripts/release-diff/collect.js @@ -0,0 +1,101 @@ +// Child process for index.js: runs inputs [start, end) through the baseline and +// the candidate build and prints one JSON line per difference. It stops after +// the first input that throws, so a trapped or half-broken WASM instance never +// leaks into the next input: the parent starts a fresh process from `next`. +const fs = require('node:fs'); +const { loadAllowlist, allows, withoutKeys } = require('./allowlist'); + +const [baselineDir, candidateDir, inputsFile, startArg, allowFile, baselineVersion] = process.argv.slice(2); +const keyRules = loadAllowlist(allowFile, baselineVersion) + .map((entry, index) => ({ ...entry, index, keys: new Set(entry.ignoreKeys || []) })) + .filter((entry) => entry.keys.size); +const inputs = JSON.parse(fs.readFileSync(inputsFile, 'utf8')); +const libs = [require(baselineDir), require(candidateDir)]; + +const FNS = { + parse: (lib, sql) => { + const { version, ...rest } = lib.parseSync(sql); + return JSON.stringify(rest); + }, + fingerprint: (lib, sql) => lib.fingerprintSync(sql), + normalize: (lib, sql) => lib.normalizeSync(sql), + scan: (lib, sql) => { + const { version, ...rest } = lib.scanSync(sql); + return JSON.stringify(rest); + }, + parsePlPgSQL: (lib, sql) => JSON.stringify(lib.parsePlPgSQLSync(sql)), +}; + +// Source file and line of a SqlError move with any C change, so only the +// message and cursor position count as behavior. +function describeError(error) { + const details = error && error.sqlDetails; + if (details) { + return { error: details.message, cursorPosition: details.cursorPosition }; + } + return { error: `${(error && error.name) || 'Error'}: ${(error && error.message) || String(error)}` }; +} + +function run(lib, fn, sql) { + try { + return { ok: FNS[fn](lib, sql) }; + } catch (error) { + return describeError(error); + } +} + +const same = (a, b) => a.ok === b.ok && a.error === b.error && a.cursorPosition === b.cursorPosition; +// Synchronous, so a line is never lost to the early exit below. +const write = (line) => fs.writeSync(1, JSON.stringify(line) + '\n'); + +// Outputs that differ only in keys an allowlist entry ignores. Checked here, +// where the whole outputs are at hand. +function ignoredBy(id, baseline, candidate) { + if (!('ok' in baseline) || !('ok' in candidate)) return undefined; + const rule = keyRules.find((entry) => allows(entry, { id, baseline, candidate }) + && withoutKeys(baseline.ok, entry.keys) === withoutKeys(candidate.ok, entry.keys)); + return rule && rule.index; +} + +// Outputs can be megabytes; report the region around the first difference. +function preview(outcome, other) { + if (!('ok' in outcome)) return outcome; + if (!('ok' in other)) return { ok: outcome.ok.slice(0, 180) + (outcome.ok.length > 180 ? '…' : '') }; + const [a, b] = [outcome.ok, other.ok]; + let i = 0; + while (i < a.length && a[i] === b[i]) i++; + const from = Math.max(0, i - 60); + return { ok: (from ? '…' : '') + a.slice(from, i + 120) + (i + 120 < a.length ? '…' : '') }; +} + +(async () => { + await Promise.all(libs.map((lib) => lib.loadModule())); + for (let i = Number(startArg); i < inputs.length; i++) { + const { id, sql, fns } = inputs[i]; + write({ type: 'at', i }); + let threw = false; + for (const fn of fns) { + const [baseline, candidate] = libs.map((lib) => run(lib, fn, sql)); + threw = threw || 'error' in baseline || 'error' in candidate; + if (!same(baseline, candidate)) { + const diffId = `${id}:${fn}`; + write({ + type: 'diff', + id: diffId, + baseline: preview(baseline, candidate), + candidate: preview(candidate, baseline), + allowedBy: ignoredBy(diffId, baseline, candidate), + }); + } + } + write({ type: 'compared', i, count: fns.length }); + if (threw && i + 1 < inputs.length) { + write({ type: 'restart', next: i + 1 }); + process.exit(0); + } + } + write({ type: 'done' }); +})().catch((error) => { + process.stderr.write(String((error && error.stack) || error) + '\n'); + process.exit(1); +}); diff --git a/scripts/release-diff/edge-cases.js b/scripts/release-diff/edge-cases.js new file mode 100644 index 00000000..0e03a547 --- /dev/null +++ b/scripts/release-diff/edge-cases.js @@ -0,0 +1,62 @@ +// Inputs the fixtures don't cover: deep nesting, long lists and large scripts, +// at sizes on both sides of the parser's depth and memory limits. A build that +// rejects an input the last release parsed (or the reverse) shows up here. +const DEPTHS = [100, 250, 500, 750, 1000, 1500, 2000, 3000, 5000, 10000]; +const SIZES = [1000, 10000, 50000]; + +const nest = (open, inner, close, n) => open.repeat(n) + inner + close.repeat(n); + +const SQL_DEPTH = { + 'plus-chain': (n) => 'SELECT 1' + '+1'.repeat(n), + 'concat-chain': (n) => "SELECT 'a'" + " || 'a'".repeat(n), + 'and-chain': (n) => 'SELECT 1 WHERE ' + Array(n).fill('a = 1').join(' AND '), + 'or-chain': (n) => 'SELECT 1 WHERE ' + Array(n).fill('a = 1').join(' OR '), + 'parens': (n) => 'SELECT ' + nest('(', '1', ')', n), + 'unary-minus': (n) => 'SELECT ' + '- '.repeat(n) + 'a', + 'not-chain': (n) => 'SELECT ' + 'NOT '.repeat(n) + 'true', + 'function-calls': (n) => 'SELECT ' + nest('f(', '1', ')', n), + 'subselects': (n) => 'SELECT ' + nest('(SELECT ', '1', ')', n), + 'arrays': (n) => 'SELECT ' + nest('ARRAY[', '1', ']', n), + 'case': (n) => 'SELECT ' + nest('CASE WHEN a THEN ', '1', ' END', n), + 'casts': (n) => 'SELECT 1' + '::int'.repeat(n), + 'joins': (n) => 'SELECT 1 FROM t0' + Array.from({ length: n }, (_, i) => ` JOIN t${i + 1} ON true`).join(''), + 'set-ops': (n) => Array(n).fill('SELECT 1').join(' UNION ALL '), + 'ctes': (n) => 'WITH ' + Array.from({ length: n }, (_, i) => `c${i} AS (SELECT 1)`).join(', ') + ' SELECT 1', + 'json-path': (n) => "SELECT j" + " -> 'a'".repeat(n), +}; + +const SQL_SIZE = { + 'in-list': (n) => 'SELECT 1 WHERE a IN (' + Array(n).fill('1').join(', ') + ')', + 'values-rows': (n) => 'VALUES ' + Array(n).fill('(1, 2)').join(', '), + 'select-list': (n) => 'SELECT ' + Array(n).fill('1').join(', '), + 'statements': (n) => 'SELECT 1;\n'.repeat(n), + 'string-literal': (n) => "SELECT '" + 'a'.repeat(n * 10) + "'", + 'comment': (n) => 'SELECT 1 /* ' + 'x'.repeat(n * 10) + ' */', + 'unicode-identifiers': (n) => 'SELECT ' + Array(n).fill('"Γ©ζΌ’ε­—πŸ™‚"').join(', '), +}; + +const PLPGSQL_DEPTH = { + 'if-blocks': (n) => nest('IF true THEN ', 'NULL;', ' END IF;', n), + 'begin-blocks': (n) => nest('BEGIN ', 'NULL;', ' END;', n), + 'loops': (n) => nest('LOOP ', 'EXIT;', ' END LOOP;', n), + 'expression': (n) => 'x := 1' + '+1'.repeat(n) + ';', +}; + +const plpgsql = (body) => + `CREATE FUNCTION f() RETURNS void LANGUAGE plpgsql AS $$ DECLARE x int; BEGIN ${body} END $$`; + +const SQL_FNS = ['parse', 'fingerprint', 'normalize', 'scan']; + +module.exports = function edgeCases() { + const cases = []; + for (const [name, make] of Object.entries(SQL_DEPTH)) { + for (const n of DEPTHS) cases.push({ id: `edge:${name}-${n}`, sql: make(n), fns: SQL_FNS }); + } + for (const [name, make] of Object.entries(SQL_SIZE)) { + for (const n of SIZES) cases.push({ id: `edge:${name}-${n}`, sql: make(n), fns: SQL_FNS }); + } + for (const [name, make] of Object.entries(PLPGSQL_DEPTH)) { + for (const n of DEPTHS) cases.push({ id: `edge:plpgsql-${name}-${n}`, sql: plpgsql(make(n)), fns: ['parsePlPgSQL'] }); + } + return cases; +}; diff --git a/scripts/release-diff/index.js b/scripts/release-diff/index.js new file mode 100644 index 00000000..82d81523 --- /dev/null +++ b/scripts/release-diff/index.js @@ -0,0 +1,301 @@ +#!/usr/bin/env node +// Release diff: runs the version's test suite and the pgsql-parser fixtures +// through the last published libpg-query and the candidate build in +// versions//wasm, and fails on any difference the allowlist doesn't name. +// +// node scripts/release-diff [--major 18] [--baseline pg18|18.1.5] +// [--fixtures ../pgsql-parser] [--allow versions/18/release-diff.allow.json] +// [--skip-tests] +const fs = require('node:fs'); +const path = require('node:path'); +const { execFileSync, spawn } = require('node:child_process'); +const edgeCases = require('./edge-cases'); +const { loadAllowlist, allows } = require('./allowlist'); + +const ROOT = path.resolve(__dirname, '../..'); +const SQL_FNS = ['parse', 'fingerprint', 'normalize', 'scan']; +const INPUT_TIMEOUT_MS = 120000; +const TEST_FILE_TIMEOUT_MS = 300000; +// A bigger JS stack than Node's default (~1 MB, still inside the 8 MB thread +// stack), so deep JSON from either build reaches the comparison instead of a +// RangeError whose depth depends on the machine. +const JS_STACK_KB = 4000; + +function parseArgs(argv) { + const args = {}; + for (let i = 0; i < argv.length; i++) { + const key = argv[i].replace(/^--/, ''); + if (key === 'skip-tests') args.skipTests = true; + else args[key] = argv[++i]; + } + return args; +} + +const args = parseArgs(process.argv.slice(2)); +const major = args.major || process.env.RELEASE_DIFF_MAJOR || '18'; +const versionDir = path.join(ROOT, 'versions', major); +const workDir = path.join(versionDir, '.release-diff'); +const pkg = JSON.parse(fs.readFileSync(path.join(versionDir, 'package.json'), 'utf8')); +const publishName = pkg['x-publish'].publishName; +const baselineSpec = args.baseline || process.env.RELEASE_DIFF_BASELINE || pkg['x-publish'].distTag; +const allowFile = path.resolve(args.allow || path.join(versionDir, 'release-diff.allow.json')); + +const sh = (cmd, argv, opts = {}) => execFileSync(cmd, argv, { encoding: 'utf8', ...opts }).trim(); + +function fetchBaseline() { + const version = JSON.parse(sh('npm', ['view', `${publishName}@${baselineSpec}`, 'version', '--json', '--loglevel=error'])); + const dir = path.join(workDir, `baseline-${version}`); + if (!fs.existsSync(path.join(dir, 'wasm', 'index.cjs'))) { + fs.rmSync(dir, { recursive: true, force: true }); + fs.mkdirSync(dir, { recursive: true }); + const tarball = sh('npm', ['pack', `${publishName}@${version}`, '--pack-destination', workDir, '--loglevel=error']).split('\n').pop(); + sh('tar', ['-xzf', path.join(workDir, tarball), '-C', dir, '--strip-components=1']); + fs.rmSync(path.join(workDir, tarball)); + } + return { version, dir }; +} + +function fixturesDir() { + const dir = args.fixtures || process.env.PGSQL_PARSER_DIR; + if (dir) return path.resolve(dir); + const clone = path.join(workDir, 'pgsql-parser'); + if (!fs.existsSync(clone)) { + sh('git', ['clone', '--depth', '1', '--filter=blob:none', '--sparse', 'https://github.com/constructive-io/pgsql-parser.git', clone]); + sh('git', ['-C', clone, 'sparse-checkout', 'set', '__fixtures__/generated', '__fixtures__/plpgsql-generated']); + } + return clone; +} + +function loadInputs(fixtures) { + const read = (file) => JSON.parse(fs.readFileSync(path.join(fixtures, '__fixtures__', file), 'utf8')); + const inputs = []; + for (const [name, sql] of Object.entries(read('generated/generated.json'))) { + inputs.push({ id: `kitchen-sink:${name}`, sql, fns: SQL_FNS }); + } + for (const [name, sql] of Object.entries(read('plpgsql-generated/generated.json'))) { + inputs.push({ id: `plpgsql:${name}`, sql, fns: ['parsePlPgSQL'] }); + } + return inputs.concat(edgeCases()); +} + +function runCollector(baselineDir, baselineVersion, inputsFile, start) { + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, [`--stack-size=${JS_STACK_KB}`, path.join(__dirname, 'collect.js'), baselineDir, versionDir, inputsFile, String(start), allowFile, baselineVersion], { + stdio: ['ignore', 'pipe', 'pipe'], + }); + const lines = []; + let buffer = ''; + let stderr = ''; + child.stdout.on('data', (chunk) => { + buffer += chunk; + const parts = buffer.split('\n'); + buffer = parts.pop(); + for (const part of parts) if (part) lines.push(JSON.parse(part)); + }); + child.stderr.on('data', (chunk) => { stderr += chunk; }); + let timer; + const idle = () => { + clearTimeout(timer); + timer = setTimeout(() => child.kill('SIGKILL'), INPUT_TIMEOUT_MS); + }; + idle(); + child.stdout.on('data', idle); + child.on('error', reject); + child.on('close', (code, signal) => { + clearTimeout(timer); + testGroups.delete(child.pid); + resolve({ lines, code, signal, stderr }); + }); + }); +} + +async function diffCorpus(baseline, inputs) { + const inputsFile = path.join(workDir, 'inputs.json'); + fs.writeFileSync(inputsFile, JSON.stringify(inputs)); + const diffs = []; + let compared = 0; + let start = 0; + while (start < inputs.length) { + const { lines, code, signal, stderr } = await runCollector(baseline.dir, baseline.version, inputsFile, start); + let at = start; + let next = null; + for (const line of lines) { + if (line.type === 'at') at = line.i; + else if (line.type === 'diff') diffs.push(line); + else if (line.type === 'compared') compared += line.count; + else if (line.type === 'restart') next = line.next; + else if (line.type === 'done') next = inputs.length; + } + if (next === null) { + // The process died inside an input: count it as a difference, since a + // release that crashes on it is one, and carry on after it. + if (at === start && !lines.length && code) throw new Error(`collector failed to start:\n${stderr}`); + const reason = signal === 'SIGKILL' ? `no result after ${INPUT_TIMEOUT_MS / 1000}s` : signal ? `signal ${signal}` : `exit code ${code}`; + diffs.push({ id: `${inputs[at].id}:*`, baseline: { error: 'unknown' }, candidate: { error: `process died (${reason})` } }); + next = at + 1; + } + start = next; + } + return { diffs, compared }; +} + +function testFiles() { + return pkg.scripts.test.split(/\s+/).filter((arg) => /^test\/.*\.js$/.test(arg)); +} + +// One file at a time with a wall-clock limit: a WASM call that never returns +// blocks the event loop, so node:test's own timeouts can't stop it. The file +// runs in its own process group so a timeout kills node:test's workers too. +const testGroups = new Set(); +for (const signal of ['SIGINT', 'SIGTERM']) { + process.on(signal, () => { + for (const pid of testGroups) { + try { process.kill(-pid, 'SIGKILL'); } catch (e) {} + } + process.exit(1); + }); +} + +function runTestFile(cwd, file, out) { + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, [ + '--test', + `--test-reporter=${path.join(__dirname, 'reporter.js')}`, + `--test-reporter-destination=${out}`, + file, + ], { cwd, stdio: 'ignore', detached: true }); + testGroups.add(child.pid); + let timedOut = false; + const timer = setTimeout(() => { + timedOut = true; + try { process.kill(-child.pid, 'SIGKILL'); } catch (e) {} + }, TEST_FILE_TIMEOUT_MS); + child.on('error', reject); + child.on('close', (code) => { + clearTimeout(timer); + testGroups.delete(child.pid); + resolve({ + status: timedOut ? 'timeout' : code === 0 ? 'pass' : `exit ${code}`, + output: fs.existsSync(out) ? fs.readFileSync(out, 'utf8') : '', + }); + }); + }); +} + +// Each file also gets a `` entry with its exit status, so a file that +// times out or fails outside a test is a difference too. +async function runTests(cwd, files, label) { + const results = new Map(); + results.fileOf = new Map(); + for (const file of files) { + const out = path.join(workDir, `tests-${label}-${path.basename(file)}.jsonl`); + fs.rmSync(out, { force: true }); + const { status, output } = await runTestFile(cwd, file, out); + results.set(file, status); + for (const line of output.split('\n')) { + if (!line) continue; + const { key, status } = JSON.parse(line); + let unique = key; + for (let n = 2; results.has(unique); n++) unique = `${key} #${n}`; + results.set(unique, status); + results.fileOf.set(unique, file); + } + } + return results; +} + +// The baseline runs the candidate's tests, so tests for new fixes fail there; +// only a test the published release passes and the candidate fails is a diff. +async function diffTests(baselineDir) { + const files = testFiles(); + fs.rmSync(path.join(baselineDir, 'test'), { recursive: true, force: true }); + fs.cpSync(path.join(versionDir, 'test'), path.join(baselineDir, 'test'), { recursive: true }); + const [baseline, candidate] = await Promise.all([runTests(baselineDir, files, 'baseline'), runTests(versionDir, files, 'candidate')]); + const diffs = []; + const filesWithDiffs = new Set(); + for (const [key, status] of baseline) { + if (status !== 'pass' || files.includes(key)) continue; + const now = candidate.get(key) || 'missing'; + if (now !== 'pass') { + diffs.push({ id: `test:${key}`, baseline: { error: 'pass' }, candidate: { error: now } }); + filesWithDiffs.add(baseline.fileOf.get(key)); + } + } + // A test diff already explains its file's non-zero exit; any other exit + // (a crash after passing tests, a timeout) is a diff of its own. + for (const file of files) { + const now = candidate.get(file) || 'missing'; + if (baseline.get(file) !== 'pass' || now === 'pass') continue; + if (now.startsWith('exit') && filesWithDiffs.has(file)) continue; + diffs.push({ id: `test:${file}`, baseline: { error: 'pass' }, candidate: { error: now } }); + } + const skipped = files.filter((file) => baseline.get(file) === 'timeout'); + return { diffs, compared: baseline.size, skipped }; +} + +function show(outcome) { + return 'ok' in outcome ? outcome.ok : JSON.stringify(outcome); +} + +function report(baselineVersion, results, allowlist) { + const failures = []; + let allowed = 0; + for (const diff of results.flatMap((result) => result.diffs)) { + const entry = diff.allowedBy !== undefined + ? allowlist[diff.allowedBy] + : allowlist.find((candidate) => !candidate.ignoreKeys && allows(candidate, diff)); + if (entry) { + entry.used++; + allowed++; + } else { + failures.push(diff); + } + } + const compared = results.reduce((sum, result) => sum + result.compared, 0); + const lines = [ + `## Release diff: ${publishName}@${baselineVersion} vs candidate ${pkg.version}`, + '', + `${compared} outputs and tests compared, ${allowed} allowed differences, ${failures.length} unexpected.`, + '', + ]; + if (failures.length) { + lines.push('| Input | Published | Candidate |', '| --- | --- | --- |'); + const cell = (text) => '`' + text.replace(/\|/g, '\\|').replace(/`/g, "'").replace(/\n/g, ' ') + '`'; + for (const diff of failures.slice(0, 200)) { + lines.push(`| ${cell(diff.id)} | ${cell(show(diff.baseline))} | ${cell(show(diff.candidate))} |`); + } + if (failures.length > 200) lines.push('', `…and ${failures.length - 200} more in report.json.`); + lines.push('', `Fix the regression, or add the difference to ${path.relative(ROOT, allowFile)} with the reason it is intended.`); + } + const skipped = results.flatMap((result) => result.skipped || []); + if (skipped.length) { + lines.push('', `Test files that timed out on ${publishName}@${baselineVersion}, so their tests were not compared: ${skipped.join(', ')}`); + } + const stale = allowlist.filter((entry) => !entry.used); + if (stale.length) { + lines.push('', 'Allowlist entries that matched nothing (remove them once the release that needed them is the baseline):'); + for (const entry of stale) lines.push(`- \`${entry.id}\``); + } + const markdown = lines.join('\n') + '\n'; + process.stdout.write(markdown); + if (process.env.GITHUB_STEP_SUMMARY) fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, markdown); + fs.writeFileSync(path.join(workDir, 'report.json'), JSON.stringify({ baseline: baselineVersion, compared, allowed, failures }, null, 2)); + return failures.length; +} + +(async () => { + if (!fs.existsSync(path.join(versionDir, 'wasm', 'index.cjs'))) { + throw new Error(`No candidate build in ${path.relative(ROOT, versionDir)}/wasm; build it first.`); + } + fs.mkdirSync(workDir, { recursive: true }); + const baseline = fetchBaseline(); + console.log(`Comparing ${publishName}@${baseline.version} with the candidate build of ${pkg.name}@${pkg.version}`); + const inputs = loadInputs(fixturesDir()); + const results = [await diffCorpus(baseline, inputs)]; + if (!args.skipTests) results.push(await diffTests(baseline.dir)); + const failures = report(baseline.version, results, loadAllowlist(allowFile, baseline.version)); + process.exit(failures ? 1 : 0); +})().catch((error) => { + console.error(error); + process.exit(1); +}); diff --git a/scripts/release-diff/reporter.js b/scripts/release-diff/reporter.js new file mode 100644 index 00000000..75fdcc08 --- /dev/null +++ b/scripts/release-diff/reporter.js @@ -0,0 +1,22 @@ +// node:test reporter for index.js: one JSON line per finished test, keyed by +// its file and the names of the suites it is nested in. +const path = require('node:path'); + +module.exports = async function* reporter(source) { + const stacks = new Map(); + for await (const event of source) { + if (!['test:start', 'test:pass', 'test:fail'].includes(event.type)) continue; + const { name, nesting, file, skip, todo } = event.data; + const fileKey = file ? path.basename(file) : ''; + if (!stacks.has(fileKey)) stacks.set(fileKey, []); + const stack = stacks.get(fileKey); + if (event.type === 'test:start') { + stack.length = nesting; + stack[nesting] = name; + continue; + } + const key = [fileKey, ...stack.slice(0, nesting), name].join(' > '); + const status = skip || todo ? 'skip' : event.type === 'test:pass' ? 'pass' : 'fail'; + yield JSON.stringify({ key, status }) + '\n'; + } +}; diff --git a/versions/18/release-diff.allow.json b/versions/18/release-diff.allow.json new file mode 100644 index 00000000..6c1ea861 --- /dev/null +++ b/versions/18/release-diff.allow.json @@ -0,0 +1,3 @@ +{ + "allow": [] +}