Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,4 @@ npm-debug.log
.claude
.openhands/
.DS_Store
versions/*/.release-diff/
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
43 changes: 43 additions & 0 deletions scripts/release-diff/allowlist.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// versions/<major>/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 };
101 changes: 101 additions & 0 deletions scripts/release-diff/collect.js
Original file line number Diff line number Diff line change
@@ -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);
});
62 changes: 62 additions & 0 deletions scripts/release-diff/edge-cases.js
Original file line number Diff line number Diff line change
@@ -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;
};
Loading
Loading