From 64e418cbfe4e9f47ea759fc1f5da89624f0e4696 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Thu, 26 Nov 2026 07:21:15 +0000 Subject: [PATCH 01/13] test(v18): compare WASM depth and recovery in Firefox and WebKit --- .github/workflows/ci.yml | 33 +++++ pnpm-lock.yaml | 47 ++++++- pnpm-workspace.yaml | 3 +- versions/18/package.json | 9 +- versions/18/test/wasm-depth-cases.js | 13 ++ versions/18/test/wasm-depth.browser.test.js | 146 ++++++++++++++++++++ 6 files changed, 247 insertions(+), 4 deletions(-) create mode 100644 versions/18/test/wasm-depth-cases.js create mode 100644 versions/18/test/wasm-depth.browser.test.js diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 36c661c8..100b6823 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -116,6 +116,39 @@ jobs: run: pnpm run test working-directory: ${{ matrix.package.path }} + browser-depth: + name: Test v18 WASM depth in ${{ matrix.browser }} + needs: build-wasm + strategy: + fail-fast: false + matrix: + include: + - browser: firefox + os: ubuntu-latest + - browser: webkit + os: macos-latest + runs-on: ${{ matrix.os }} + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '20.x' + - uses: pnpm/action-setup@v2 + with: + version: 8.15.1 + - run: pnpm install --frozen-lockfile + - uses: actions/download-artifact@v4 + with: + name: wasm-artifacts-v18 + path: versions/18/wasm/ + - run: pnpm --dir versions/18 exec playwright install --with-deps "$BROWSER" + env: + BROWSER: ${{ matrix.browser }} + - run: pnpm --dir versions/18 test:browser + env: + BROWSER: ${{ matrix.browser }} + release-diff: name: Release diff v18 vs published libpg-query 🔬 needs: build-wasm diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 54079faa..b561c72d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -164,6 +164,16 @@ importers: '@pgsql/types': specifier: ^18.0.0 version: 18.0.0 + devDependencies: + esbuild-wasm: + specifier: 0.27.7 + version: 0.27.7 + libpg-query-baseline: + specifier: npm:libpg-query@18.1.5 + version: /libpg-query@18.1.5 + playwright: + specifier: 1.61.1 + version: 1.61.1 packages: @@ -405,7 +415,6 @@ packages: /@pgsql/types@18.0.0: resolution: {integrity: sha512-jtAY4JU7jdVYZ/Vv3zlZqVP+FRWZokyCLKPPCnAApiaJAElpyyiMC3HRiquBu29kSrVs+rkqZD50SUIb/zyEGw==} - dev: false /@pkgjs/parseargs@0.11.0: resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==} @@ -642,6 +651,12 @@ packages: resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==} dev: true + /esbuild-wasm@0.27.7: + resolution: {integrity: sha512-1k03e2/tGz+sLz3/xzoZmUsIqtaGIvJa8k4UqUeqCUry83nHmlxQYZUUES0WBFUYilSQUf7nDUGAciIIklljSg==} + engines: {node: '>=18'} + hasBin: true + dev: true + /escalade@3.2.0: resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} engines: {node: '>=6'} @@ -659,6 +674,14 @@ packages: resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==} dev: true + /fsevents@2.3.2: + resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + requiresBuild: true + dev: true + optional: true + /get-caller-file@2.0.5: resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} engines: {node: 6.* || 8.* || >= 10.*} @@ -755,6 +778,12 @@ packages: hasBin: true dev: true + /libpg-query@18.1.5: + resolution: {integrity: sha512-xsksgH106LyVUylIp2bJz1MPFmVVIGKbB8belGWmh+J8/i38w8eM1twDIBnd97tzeNQFctH9MWKMthl22+fWcQ==} + dependencies: + '@pgsql/types': 18.0.0 + dev: true + /long@5.3.2: resolution: {integrity: sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==} dev: true @@ -887,6 +916,22 @@ packages: resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} dev: true + /playwright-core@1.61.1: + resolution: {integrity: sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==} + engines: {node: '>=18'} + hasBin: true + dev: true + + /playwright@1.61.1: + resolution: {integrity: sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==} + engines: {node: '>=18'} + hasBin: true + dependencies: + playwright-core: 1.61.1 + optionalDependencies: + fsevents: 2.3.2 + dev: true + /pnpm-policy@0.2.2: resolution: {integrity: sha512-Fj5/ACIZG/AGynTvhT8/7fJTf8ya3jG/Mkq/OMNVZhfTTJ1oniRTsKBHlXGF4sSecvIFqkmeHpn8CsQFwGcENA==} hasBin: true diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index c7b2cc00..62dc74b4 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -25,7 +25,7 @@ packages: # Most malicious releases are found and yanked well inside that window. minimumReleaseAge: 2880 -# Exempt from the wait: 6 scope glob(s), 5 first-party package(s). +# Exempt from the wait: 6 scope glob(s), 6 first-party package(s). # First-party membership comes from what pyramation publishes on npm — waiting on your own release protects nothing. minimumReleaseAgeExclude: - "@constructive-db/*" @@ -34,6 +34,7 @@ minimumReleaseAgeExclude: - "@pgpm/*" - "@pgpmjs/*" - "@pgsql/*" + - libpg-query - nested-obj - pg-proto-parser - pnpm-policy diff --git a/versions/18/package.json b/versions/18/package.json index 8601dc38..2cb56c69 100644 --- a/versions/18/package.json +++ b/versions/18/package.json @@ -31,7 +31,8 @@ "wasm:rebuild": "pnpm wasm:make rebuild", "wasm:clean": "pnpm wasm:make clean", "wasm:clean-cache": "pnpm wasm:make clean-cache", - "test": "node --test test/parsing.test.js test/pg18.test.js test/fingerprint.test.js test/normalize.test.js test/plpgsql.test.js test/scan.test.js test/errors.test.js test/input-encoding.test.js test/wasm-recovery.test.js test/load-module.test.js" + "test": "node --test test/parsing.test.js test/pg18.test.js test/fingerprint.test.js test/normalize.test.js test/plpgsql.test.js test/scan.test.js test/errors.test.js test/input-encoding.test.js test/wasm-recovery.test.js test/load-module.test.js", + "test:browser": "node --test test/wasm-depth.browser.test.js" }, "author": "Constructive ", "license": "MIT", @@ -39,7 +40,11 @@ "type": "git", "url": "git://github.com/constructive-io/libpg-query-node.git" }, - "devDependencies": {}, + "devDependencies": { + "esbuild-wasm": "0.27.7", + "libpg-query-baseline": "npm:libpg-query@18.1.5", + "playwright": "1.61.1" + }, "dependencies": { "@pgsql/types": "^18.0.0" }, diff --git a/versions/18/test/wasm-depth-cases.js b/versions/18/test/wasm-depth-cases.js new file mode 100644 index 00000000..1dc10140 --- /dev/null +++ b/versions/18/test/wasm-depth-cases.js @@ -0,0 +1,13 @@ +const chained = (depth) => 'SELECT 1' + '+1'.repeat(depth); +const subqueries = (depth) => 'SELECT ' + '(SELECT '.repeat(depth) + '1' + ')'.repeat(depth); +const calls = (depth) => 'SELECT ' + 'f('.repeat(depth) + '1' + ')'.repeat(depth); + +const blocks = Object.fromEntries(Object.entries({ + 'IF blocks': ['IF true THEN ', 'NULL;', ' END IF;'], + 'BEGIN blocks': ['BEGIN ', 'NULL;', ' END;'], + loops: ['LOOP ', 'EXIT;', ' END LOOP;'], +}).map(([name, [open, body, close]]) => [name, (depth) => + 'CREATE FUNCTION f() RETURNS void LANGUAGE plpgsql AS $$ BEGIN ' + + open.repeat(depth) + body + close.repeat(depth) + ' END $$'])); + +module.exports = { chained, subqueries, calls, blocks }; diff --git a/versions/18/test/wasm-depth.browser.test.js b/versions/18/test/wasm-depth.browser.test.js new file mode 100644 index 00000000..90578600 --- /dev/null +++ b/versions/18/test/wasm-depth.browser.test.js @@ -0,0 +1,146 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const path = require('node:path'); +const { appendFileSync } = require('node:fs'); +const { build } = require('esbuild-wasm'); +const { firefox, webkit } = require('playwright'); +const { chained, subqueries, calls, blocks } = require('./wasm-depth-cases'); + +const baseline = require('libpg-query-baseline/package.json').version; +const builds = { + [baseline]: path.dirname(require.resolve('libpg-query-baseline')), + candidate: path.resolve(__dirname, '../wasm'), +}; +const cases = [ + ['Chained operators', 'parseSync', chained, 4000, 100000], + ['Nested subqueries', 'parseSync', subqueries, 1000, 10000], + ['Nested function calls', 'parseSync', calls, 2000, 10000], + ...Object.entries(blocks).map(([name, sql]) => [name, 'parsePlPgSQLSync', sql, 1000, 10000]), + ['Normalize operators', 'normalizeSync', chained, 100, 100000], + ['Normalize subqueries', 'normalizeSync', subqueries, 100, 10000], +]; + +async function openParser(browser, dir) { + const { outputFiles } = await build({ + entryPoints: [path.join(dir, 'index.js')], + bundle: true, + format: 'esm', + platform: 'browser', + external: ['node:*'], + write: false, + }); + const page = await browser.newPage(); + const origin = 'http://libpg-query.test'; + await page.route(origin + '/**', (route) => { + switch (new URL(route.request().url()).pathname) { + case '/': return route.fulfill({ contentType: 'text/html', body: '' }); + case '/parser.js': return route.fulfill({ contentType: 'text/javascript', body: outputFiles[0].text }); + case '/libpg-query.wasm': return route.fulfill({ + contentType: 'application/wasm', path: path.join(dir, 'libpg-query.wasm'), + }); + default: return route.abort(); + } + }); + await page.goto(origin); + return page; +} + +async function probe(page, { method, queries, expectedParameters, fresh = false, repeats = 1 }) { + return page.evaluate(async ({ method, queries, expectedParameters, fresh, repeats }) => { + // An import with a new URL gives each input family its own WASM instance. + if (fresh || !globalThis.parser) { + globalThis.parser = await import('/parser.js?' + (globalThis.instance = (globalThis.instance || 0) + 1)); + await globalThis.parser.loadModule(); + } + const lib = globalThis.parser; + const results = []; + for (let i = 0; i < queries.length; i++) { + const sql = queries[i]; + for (let j = 0; j < repeats; j++) { + try { + const result = await lib[method](sql); + const valid = method === 'normalizeSync' || method === 'normalize' + ? typeof result === 'string' && result.startsWith('SELECT ') && + (result.match(/\$/g) || []).length === expectedParameters?.[i] + : method === 'parsePlPgSQLSync' ? result.plpgsql_funcs?.length === 1 : result.stmts?.length === 1; + results.push(valid ? null : { message: typeof result === 'string' ? result.slice(0, 120) : 'Unexpected result' }); + } catch (error) { + results.push({ name: error.name, message: error.message, sqlError: error instanceof lib.SqlError }); + } + if (lib.parseSync('SELECT 1').stmts.length !== 1) throw new Error('Parser did not recover'); + } + } + if ((await lib.parse('SELECT 1')).stmts.length !== 1) throw new Error('Async parse did not recover'); + return results; + }, { method, queries, expectedParameters, fresh, repeats }); +} + +function assertLimit(error, version, name) { + assert.ok(error, `${version}: ${name} unexpectedly succeeded`); + if (version === 'candidate') { + assert.equal(error.message, 'stack depth limit exceeded', name); + assert.equal(error.sqlError, true, name); + } else { + assert.match(error.message, /call stack|too much recursion|stack depth limit exceeded|^memory exhausted at or near/i, name); + } +} + +async function measure(page, version, name, method, sql, floor, ceiling) { + const tryDepth = async (depth, fresh) => (await probe(page, { + method, + queries: [sql(depth)], + expectedParameters: [sql === chained ? depth + 1 : 1], + fresh, + }))[0]; + assert.equal(await tryDepth(floor, true), null, `${version}: ${name} at depth ${floor}`); + + // WASM tiering can move the host overflow boundary by a few frames. Compare + // depths at 100-level resolution rather than treating frame counts as an ABI. + const step = 100; + let low = floor / step; + let high = ceiling / step; + while (high - low > 1) { + const mid = Math.floor((low + high) / 2); + const error = await tryDepth(mid * step); + if (!error) low = mid; + else high = mid; + } + return { depth: low * step, error: await tryDepth(ceiling) }; +} + +const engines = { firefox, webkit }; +const selected = process.env.BROWSER; +if (selected && !Object.hasOwn(engines, selected)) throw new Error(`Unknown browser: ${selected}`); + +for (const [name, engine] of Object.entries(engines)) { + if (selected && name !== selected) continue; + test(name, { timeout: 240000 }, async (t) => { + const browser = await engine.launch(); + t.after(() => browser.close()); + const pages = Object.fromEntries(await Promise.all(Object.entries(builds).map(async ([version, dir]) => + [version, await openParser(browser, dir)]))); + const rows = [`| ${name} ${browser.version()} | ${baseline} | Candidate |`, '| --- | ---: | ---: |']; + for (const [label, method, sql, floor, ceiling] of cases) { + await t.test(label, async () => { + const published = await measure(pages[baseline], baseline, label, method, sql, floor, ceiling); + const candidate = await measure(pages.candidate, 'candidate', label, method, sql, floor, ceiling); + rows.push(`| ${label} | ${published.depth} | ${candidate.depth} |`); + assertLimit(published.error, baseline, label); + assertLimit(candidate.error, 'candidate', label); + assert.ok(candidate.depth >= published.depth, `${label}: depth fell from ${published.depth} to ${candidate.depth}`); + }); + } + await t.test('recovers after repeated synchronous and asynchronous overflows', async () => { + for (const [version, page] of Object.entries(pages)) { + const options = { queries: [chained(100000)] }; + const errors = await probe(page, { ...options, method: 'parseSync', fresh: true, repeats: 60 }); + for (const error of errors) assertLimit(error, version, 'parseSync'); + const [error] = await probe(page, { ...options, method: 'normalize' }); + assertLimit(error, version, 'normalize'); + } + }); + const summary = rows.join('\n') + '\n'; + console.log('\n' + summary); + if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, summary); + }); +} From 535aeb5d6037d1a3b63adc1cc9847559e5cf0e5c Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Thu, 26 Nov 2026 07:27:57 +0000 Subject: [PATCH 02/13] test(v18): isolate depth and preserve PostgreSQL grammar diagnostics --- .github/workflows/ci.yml | 8 +- versions/18/test/plpgsql.test.js | 8 ++ versions/18/test/wasm-depth.browser.test.js | 148 +++++++++++++------- 3 files changed, 106 insertions(+), 58 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 100b6823..1d82f5c5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -129,6 +129,8 @@ jobs: os: macos-latest runs-on: ${{ matrix.os }} timeout-minutes: 15 + env: + WASM_TEST_BROWSER: ${{ matrix.browser }} steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -142,12 +144,8 @@ jobs: with: name: wasm-artifacts-v18 path: versions/18/wasm/ - - run: pnpm --dir versions/18 exec playwright install --with-deps "$BROWSER" - env: - BROWSER: ${{ matrix.browser }} + - run: pnpm --dir versions/18 exec playwright install --with-deps "$WASM_TEST_BROWSER" - run: pnpm --dir versions/18 test:browser - env: - BROWSER: ${{ matrix.browser }} release-diff: name: Release diff v18 vs published libpg-query 🔬 diff --git a/versions/18/test/plpgsql.test.js b/versions/18/test/plpgsql.test.js index e3235c83..475c0f6e 100644 --- a/versions/18/test/plpgsql.test.js +++ b/versions/18/test/plpgsql.test.js @@ -1,12 +1,20 @@ const query = require("../"); const { describe, it, before, after, beforeEach, afterEach } = require('node:test'); const assert = require('node:assert/strict'); +const { blocks } = require('./wasm-depth-cases'); describe("PL/pgSQL Parsing", () => { before(async () => { await query.parse("SELECT 1"); }); + it("preserves PostgreSQL's grammar limit as a SqlError", async () => { + const sql = blocks.loops(10000); + const expected = { name: "SqlError", message: 'memory exhausted at or near "LOOP"' }; + assert.throws(() => query.parsePlPgSQLSync(sql), expected); + await assert.rejects(query.parsePlPgSQL(sql), expected); + }); + describe("Sync PL/pgSQL Parsing", () => { it("should parse a simple PL/pgSQL function", () => { const funcSql = ` diff --git a/versions/18/test/wasm-depth.browser.test.js b/versions/18/test/wasm-depth.browser.test.js index 90578600..caeb2cb9 100644 --- a/versions/18/test/wasm-depth.browser.test.js +++ b/versions/18/test/wasm-depth.browser.test.js @@ -12,11 +12,11 @@ const builds = { candidate: path.resolve(__dirname, '../wasm'), }; const cases = [ - ['Chained operators', 'parseSync', chained, 4000, 100000], + ['Chained operators', 'parseSync', chained, 4000, 32000], ['Nested subqueries', 'parseSync', subqueries, 1000, 10000], ['Nested function calls', 'parseSync', calls, 2000, 10000], ...Object.entries(blocks).map(([name, sql]) => [name, 'parsePlPgSQLSync', sql, 1000, 10000]), - ['Normalize operators', 'normalizeSync', chained, 100, 100000], + ['Normalize operators', 'normalizeSync', chained, 100, 32000], ['Normalize subqueries', 'normalizeSync', subqueries, 100, 10000], ]; @@ -45,71 +45,89 @@ async function openParser(browser, dir) { return page; } -async function probe(page, { method, queries, expectedParameters, fresh = false, repeats = 1 }) { - return page.evaluate(async ({ method, queries, expectedParameters, fresh, repeats }) => { - // An import with a new URL gives each input family its own WASM instance. - if (fresh || !globalThis.parser) { - globalThis.parser = await import('/parser.js?' + (globalThis.instance = (globalThis.instance || 0) + 1)); +async function probe(page, { method, query, expectedParameters, fresh = false, warmup }) { + if (fresh) await page.reload(); + return page.evaluate(async ({ method, query, expectedParameters, warmup }) => { + if (!globalThis.parser) { + globalThis.parser = await import('/parser.js'); await globalThis.parser.loadModule(); } const lib = globalThis.parser; - const results = []; - for (let i = 0; i < queries.length; i++) { - const sql = queries[i]; - for (let j = 0; j < repeats; j++) { - try { - const result = await lib[method](sql); - const valid = method === 'normalizeSync' || method === 'normalize' - ? typeof result === 'string' && result.startsWith('SELECT ') && - (result.match(/\$/g) || []).length === expectedParameters?.[i] - : method === 'parsePlPgSQLSync' ? result.plpgsql_funcs?.length === 1 : result.stmts?.length === 1; - results.push(valid ? null : { message: typeof result === 'string' ? result.slice(0, 120) : 'Unexpected result' }); - } catch (error) { - results.push({ name: error.name, message: error.message, sqlError: error instanceof lib.SqlError }); - } - if (lib.parseSync('SELECT 1').stmts.length !== 1) throw new Error('Parser did not recover'); - } + if (warmup) { + for (let i = 0; i < 20; i++) lib[method](warmup); + } + let error = null; + let result; + try { + result = await lib[method](query); + } catch (e) { + error = { name: e.name, message: e.message, sqlError: e instanceof lib.SqlError }; + } + assertRecovered(lib.parseSync('SELECT 1')); + assertRecovered(await lib.parse('SELECT 1')); + if (error) return error; + const valid = method.startsWith('normalize') + ? typeof result === 'string' && result.startsWith('SELECT ') && + (expectedParameters === undefined || (result.match(/\$/g) || []).length === expectedParameters) + : method.startsWith('parsePlPgSQL') ? result.plpgsql_funcs?.length === 1 : result.stmts?.length === 1; + if (!valid) throw new Error(`${method} returned an unexpected result`); + return null; + + function assertRecovered(result) { + if (result.stmts.length !== 1) throw new Error('Parser did not recover'); } - if ((await lib.parse('SELECT 1')).stmts.length !== 1) throw new Error('Async parse did not recover'); - return results; - }, { method, queries, expectedParameters, fresh, repeats }); + }, { method, query, expectedParameters, warmup }); } -function assertLimit(error, version, name) { +const grammarLimit = /^memory exhausted at or near /; +const depthStep = 100; + +function assertLimit(error, version, name, publishedError) { assert.ok(error, `${version}: ${name} unexpectedly succeeded`); if (version === 'candidate') { - assert.equal(error.message, 'stack depth limit exceeded', name); + // For the fixed grammar stack limit, preserve PostgreSQL's own diagnostic. + const message = grammarLimit.test(error.message) && grammarLimit.test(publishedError?.message) + ? publishedError.message : 'stack depth limit exceeded'; + assert.equal(error.message, message, name); assert.equal(error.sqlError, true, name); } else { - assert.match(error.message, /call stack|too much recursion|stack depth limit exceeded|^memory exhausted at or near/i, name); + assert.ok(grammarLimit.test(error.message) || + /call stack|too much recursion|stack depth limit exceeded/i.test(error.message), `${name}: ${error.message}`); } } async function measure(page, version, name, method, sql, floor, ceiling) { - const tryDepth = async (depth, fresh) => (await probe(page, { + const tryDepth = (depth, warmup) => probe(page, { method, - queries: [sql(depth)], - expectedParameters: [sql === chained ? depth + 1 : 1], - fresh, - }))[0]; - assert.equal(await tryDepth(floor, true), null, `${version}: ${name} at depth ${floor}`); + query: sql(depth), + expectedParameters: sql === chained ? depth + 1 : 1, + fresh: true, + warmup, + }); + assert.equal(await tryDepth(floor), null, `${version}: ${name} at depth ${floor}`); // WASM tiering can move the host overflow boundary by a few frames. Compare // depths at 100-level resolution rather than treating frame counts as an ABI. - const step = 100; - let low = floor / step; - let high = ceiling / step; + let low = floor / depthStep; + let high = ceiling / depthStep; + const warmup = sql(floor); + const limit = await tryDepth(ceiling, warmup); + let error = limit; + assert.ok(limit, `${version}: ${name} exceeded the depth search ceiling ${ceiling}`); while (high - low > 1) { const mid = Math.floor((low + high) / 2); - const error = await tryDepth(mid * step); - if (!error) low = mid; - else high = mid; + const result = await tryDepth(mid * depthStep, warmup); + if (!result) low = mid; + else { + error = result; + high = mid; + } } - return { depth: low * step, error: await tryDepth(ceiling) }; + return { depth: low * depthStep, error, limit }; } const engines = { firefox, webkit }; -const selected = process.env.BROWSER; +const selected = process.env.WASM_TEST_BROWSER; if (selected && !Object.hasOwn(engines, selected)) throw new Error(`Unknown browser: ${selected}`); for (const [name, engine] of Object.entries(engines)) { @@ -126,21 +144,45 @@ for (const [name, engine] of Object.entries(engines)) { const candidate = await measure(pages.candidate, 'candidate', label, method, sql, floor, ceiling); rows.push(`| ${label} | ${published.depth} | ${candidate.depth} |`); assertLimit(published.error, baseline, label); - assertLimit(candidate.error, 'candidate', label); - assert.ok(candidate.depth >= published.depth, `${label}: depth fell from ${published.depth} to ${candidate.depth}`); + let publishedDiagnostic = published.limit; + if (method === 'normalizeSync' && grammarLimit.test(candidate.limit.message) && + !grammarLimit.test(publishedDiagnostic.message)) { + // The old normalizer may overflow before the underlying SQL grammar does. + publishedDiagnostic = await probe(pages[baseline], { + method: 'parseSync', query: sql(ceiling), fresh: true, + }); + } + assertLimit(candidate.error, 'candidate', label, publishedDiagnostic); + assertLimit(candidate.limit, 'candidate', label, publishedDiagnostic); + assert.ok(candidate.depth >= published.depth - depthStep, + `${label}: depth fell from ${published.depth} to ${candidate.depth}`); + if (method === 'normalizeSync') { + const overflow = await probe(pages.candidate, { method, query: sql(ceiling), fresh: true }); + assertLimit(overflow, 'candidate', label, publishedDiagnostic); + const depth = Math.max(floor, published.depth - depthStep); + const afterOverflow = await probe(pages.candidate, { + method, query: sql(depth), expectedParameters: sql === chained ? depth + 1 : 1, + }); + assert.equal(afterOverflow, null, `${label}: cannot reach published depth after overflow`); + } }); } - await t.test('recovers after repeated synchronous and asynchronous overflows', async () => { + const summary = rows.join('\n') + '\n'; + console.log('\n' + summary); + if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, summary); + await t.test('recovers after synchronous and asynchronous overflows', async () => { for (const [version, page] of Object.entries(pages)) { - const options = { queries: [chained(100000)] }; - const errors = await probe(page, { ...options, method: 'parseSync', fresh: true, repeats: 60 }); - for (const error of errors) assertLimit(error, version, 'parseSync'); - const [error] = await probe(page, { ...options, method: 'normalize' }); + const query = chained(32000); + // 18.1.5 reuses an instance after a host overflow. Measure recovery from + // one overflow there, then repeat on the candidate across browser tasks. + const attempts = version === 'candidate' ? 8 : 1; + for (let i = 0; i < attempts; i++) { + const error = await probe(page, { query, method: 'parseSync', fresh: i === 0 }); + assertLimit(error, version, 'parseSync'); + } + const error = await probe(page, { query, method: 'normalize', fresh: version !== 'candidate' }); assertLimit(error, version, 'normalize'); } }); - const summary = rows.join('\n') + '\n'; - console.log('\n' + summary); - if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, summary); }); } From a7be2bc642b9ac0c61ead56bca77db744ee58d95 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Thu, 26 Nov 2026 07:28:38 +0000 Subject: [PATCH 03/13] test(v18): recognize 18.1.5 normalization diagnostics returned as strings --- versions/18/test/wasm-depth.browser.test.js | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/versions/18/test/wasm-depth.browser.test.js b/versions/18/test/wasm-depth.browser.test.js index caeb2cb9..c1c91077 100644 --- a/versions/18/test/wasm-depth.browser.test.js +++ b/versions/18/test/wasm-depth.browser.test.js @@ -66,6 +66,11 @@ async function probe(page, { method, query, expectedParameters, fresh = false, w assertRecovered(lib.parseSync('SELECT 1')); assertRecovered(await lib.parse('SELECT 1')); if (error) return error; + // 18.1.5 can return a diagnostic string from normalize rather than throw it. + if (typeof result === 'string' && + (result.startsWith('memory exhausted at or near ') || result === 'stack depth limit exceeded')) { + return { message: result, sqlError: false }; + } const valid = method.startsWith('normalize') ? typeof result === 'string' && result.startsWith('SELECT ') && (expectedParameters === undefined || (result.match(/\$/g) || []).length === expectedParameters) @@ -106,8 +111,8 @@ async function measure(page, version, name, method, sql, floor, ceiling) { }); assert.equal(await tryDepth(floor), null, `${version}: ${name} at depth ${floor}`); - // WASM tiering can move the host overflow boundary by a few frames. Compare - // depths at 100-level resolution rather than treating frame counts as an ABI. + // Warm each instance before probing: tiering changes host frame sizes. + // Report the resulting estimates on a 100-level grid. let low = floor / depthStep; let high = ceiling / depthStep; const warmup = sql(floor); @@ -144,6 +149,7 @@ for (const [name, engine] of Object.entries(engines)) { const candidate = await measure(pages.candidate, 'candidate', label, method, sql, floor, ceiling); rows.push(`| ${label} | ${published.depth} | ${candidate.depth} |`); assertLimit(published.error, baseline, label); + assertLimit(published.limit, baseline, label); let publishedDiagnostic = published.limit; if (method === 'normalizeSync' && grammarLimit.test(candidate.limit.message) && !grammarLimit.test(publishedDiagnostic.message)) { From dcab3dc94e32dc43c97f8f9ed10bb962d25248ce Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Thu, 26 Nov 2026 07:28:38 +0000 Subject: [PATCH 04/13] fix(v18): preserve PL/pgSQL depth diagnostics as SqlError --- templates/full/index.ts | 19 +++++++++++-------- versions/18/src/index.ts | 19 +++++++++++-------- 2 files changed, 22 insertions(+), 16 deletions(-) diff --git a/templates/full/index.ts b/templates/full/index.ts index baff5223..5849b46e 100644 --- a/templates/full/index.ts +++ b/templates/full/index.ts @@ -253,6 +253,15 @@ function outOfMemoryError(): Error { return error; } +function plpgsqlError(message: string): Error { + if (message === 'out of memory') return outOfMemoryError(); + // The PL/pgSQL C API gives the JS wrapper only the diagnostic text. + if (message === 'stack depth limit exceeded' || message.startsWith('memory exhausted at or near ')) { + return new SqlError(message); + } + return new Error(message); +} + function ensureLoaded() { if (wasmModule) return; if (memoryLimitError) throw memoryLimitError; @@ -447,10 +456,7 @@ export const parsePlPgSQL = awaitInit(async (query: string): Promise Date: Thu, 26 Nov 2026 07:31:35 +0000 Subject: [PATCH 05/13] test(v18): record the intended PL/pgSQL error type change --- versions/18/release-diff.allow.json | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/versions/18/release-diff.allow.json b/versions/18/release-diff.allow.json index 20d8b73f..2763311e 100644 --- a/versions/18/release-diff.allow.json +++ b/versions/18/release-diff.allow.json @@ -1,5 +1,26 @@ { "allow": [ + { + "id": "edge:plpgsql-if-blocks-*:parsePlPgSQL", + "baseline": "18.2.7", + "published": "Error: memory exhausted at or near \"THEN\"", + "candidate": "SqlError: memory exhausted at or near \"THEN\"", + "reason": "The PostgreSQL grammar limit is reported as a SqlError with its existing diagnostic" + }, + { + "id": "edge:plpgsql-begin-blocks-*:parsePlPgSQL", + "baseline": "18.2.7", + "published": "Error: memory exhausted at or near \"BEGIN\"", + "candidate": "SqlError: memory exhausted at or near \"BEGIN\"", + "reason": "The PostgreSQL grammar limit is reported as a SqlError with its existing diagnostic" + }, + { + "id": "edge:plpgsql-loops-*:parsePlPgSQL", + "baseline": "18.2.7", + "published": "Error: memory exhausted at or near \"LOOP\"", + "candidate": "SqlError: memory exhausted at or near \"LOOP\"", + "reason": "The PostgreSQL grammar limit is reported as a SqlError with its existing diagnostic" + }, { "id": [ "edge:*:parse", From fd94108df2faf793f697bbd806b41f26da2fb7de Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Thu, 26 Nov 2026 07:32:54 +0000 Subject: [PATCH 06/13] test(v18): exercise the normalizer after a real host overflow --- versions/18/test/wasm-depth.browser.test.js | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/versions/18/test/wasm-depth.browser.test.js b/versions/18/test/wasm-depth.browser.test.js index c1c91077..f14c262f 100644 --- a/versions/18/test/wasm-depth.browser.test.js +++ b/versions/18/test/wasm-depth.browser.test.js @@ -163,10 +163,15 @@ for (const [name, engine] of Object.entries(engines)) { assert.ok(candidate.depth >= published.depth - depthStep, `${label}: depth fell from ${published.depth} to ${candidate.depth}`); if (method === 'normalizeSync') { - const overflow = await probe(pages.candidate, { method, query: sql(ceiling), fresh: true }); - assertLimit(overflow, 'candidate', label, publishedDiagnostic); + const page = pages.candidate; + const warmup = sql(floor); + assert.equal(await probe(page, { method, query: warmup, warmup, fresh: true }), null); + // A grammar error may leave the original instance intact. Force a + // host overflow after warming the code, then exercise the replacement. + const overflow = await probe(page, { method: 'parseSync', query: chained(32000) }); + assertLimit(overflow, 'candidate', label); const depth = Math.max(floor, published.depth - depthStep); - const afterOverflow = await probe(pages.candidate, { + const afterOverflow = await probe(page, { method, query: sql(depth), expectedParameters: sql === chained ? depth + 1 : 1, }); assert.equal(afterOverflow, null, `${label}: cannot reach published depth after overflow`); From 26b17776e379e3be254b651eea43f6a5d04c315d Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Thu, 26 Nov 2026 07:36:09 +0000 Subject: [PATCH 07/13] test(v18): confirm that depth losses survive WASM tiering --- versions/18/test/wasm-depth.browser.test.js | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/versions/18/test/wasm-depth.browser.test.js b/versions/18/test/wasm-depth.browser.test.js index f14c262f..a841cdc3 100644 --- a/versions/18/test/wasm-depth.browser.test.js +++ b/versions/18/test/wasm-depth.browser.test.js @@ -55,6 +55,8 @@ async function probe(page, { method, query, expectedParameters, fresh = false, w const lib = globalThis.parser; if (warmup) { for (let i = 0; i < 20; i++) lib[method](warmup); + // WebKit can finish compiling a new tier while the probe is running. + await new Promise(resolve => setTimeout(resolve, 20)); } let error = null; let result; @@ -137,7 +139,7 @@ if (selected && !Object.hasOwn(engines, selected)) throw new Error(`Unknown brow for (const [name, engine] of Object.entries(engines)) { if (selected && name !== selected) continue; - test(name, { timeout: 240000 }, async (t) => { + test(name, { timeout: 360000 }, async (t) => { const browser = await engine.launch(); t.after(() => browser.close()); const pages = Object.fromEntries(await Promise.all(Object.entries(builds).map(async ([version, dir]) => @@ -145,8 +147,16 @@ for (const [name, engine] of Object.entries(engines)) { const rows = [`| ${name} ${browser.version()} | ${baseline} | Candidate |`, '| --- | ---: | ---: |']; for (const [label, method, sql, floor, ceiling] of cases) { await t.test(label, async () => { - const published = await measure(pages[baseline], baseline, label, method, sql, floor, ceiling); - const candidate = await measure(pages.candidate, 'candidate', label, method, sql, floor, ceiling); + const run = version => measure(pages[version], version, label, method, sql, floor, ceiling); + let published = await run(baseline); + let candidate = await run('candidate'); + if (candidate.depth < published.depth - depthStep) { + // A single measurement can straddle WebKit's concurrent WASM tier-up. + // Require the loss to reproduce in the median of three searches. + const median = results => results.sort((a, b) => a.depth - b.depth)[1]; + published = median([published, await run(baseline), await run(baseline)]); + candidate = median([candidate, await run('candidate'), await run('candidate')]); + } rows.push(`| ${label} | ${published.depth} | ${candidate.depth} |`); assertLimit(published.error, baseline, label); assertLimit(published.limit, baseline, label); From bf2418d55ac11f7ec13031bb20f042b9cc91d851 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Thu, 26 Nov 2026 07:47:01 +0000 Subject: [PATCH 08/13] test(v18): dispose of each browser depth case before the next --- versions/18/test/wasm-depth.browser.test.js | 27 ++++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/versions/18/test/wasm-depth.browser.test.js b/versions/18/test/wasm-depth.browser.test.js index a841cdc3..576a55a0 100644 --- a/versions/18/test/wasm-depth.browser.test.js +++ b/versions/18/test/wasm-depth.browser.test.js @@ -20,7 +20,7 @@ const cases = [ ['Normalize subqueries', 'normalizeSync', subqueries, 100, 10000], ]; -async function openParser(browser, dir) { +async function bundleParser(dir) { const { outputFiles } = await build({ entryPoints: [path.join(dir, 'index.js')], bundle: true, @@ -29,12 +29,16 @@ async function openParser(browser, dir) { external: ['node:*'], write: false, }); + return outputFiles[0].text; +} + +async function openParser(browser, dir, script) { const page = await browser.newPage(); const origin = 'http://libpg-query.test'; await page.route(origin + '/**', (route) => { switch (new URL(route.request().url()).pathname) { case '/': return route.fulfill({ contentType: 'text/html', body: '' }); - case '/parser.js': return route.fulfill({ contentType: 'text/javascript', body: outputFiles[0].text }); + case '/parser.js': return route.fulfill({ contentType: 'text/javascript', body: script }); case '/libpg-query.wasm': return route.fulfill({ contentType: 'application/wasm', path: path.join(dir, 'libpg-query.wasm'), }); @@ -142,11 +146,21 @@ for (const [name, engine] of Object.entries(engines)) { test(name, { timeout: 360000 }, async (t) => { const browser = await engine.launch(); t.after(() => browser.close()); - const pages = Object.fromEntries(await Promise.all(Object.entries(builds).map(async ([version, dir]) => - [version, await openParser(browser, dir)]))); + const bundles = await Promise.all(Object.entries(builds).map(async ([version, dir]) => + [version, dir, await bundleParser(dir)])); + const openPages = async (subtest) => Object.fromEntries(await Promise.all( + bundles.map(async ([version, dir, script]) => { + const page = await openParser(browser, dir, script); + subtest.after(() => page.context().close()); + return [version, page]; + }) + )); const rows = [`| ${name} ${browser.version()} | ${baseline} | Candidate |`, '| --- | ---: | ---: |']; for (const [label, method, sql, floor, ceiling] of cases) { - await t.test(label, async () => { + await t.test(label, async (subtest) => { + // Don't retain browser resources from earlier searches. Each search + // reloads the page and instantiates a fresh WASM heap for each probe. + const pages = await openPages(subtest); const run = version => measure(pages[version], version, label, method, sql, floor, ceiling); let published = await run(baseline); let candidate = await run('candidate'); @@ -191,7 +205,8 @@ for (const [name, engine] of Object.entries(engines)) { const summary = rows.join('\n') + '\n'; console.log('\n' + summary); if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, summary); - await t.test('recovers after synchronous and asynchronous overflows', async () => { + await t.test('recovers after synchronous and asynchronous overflows', async (subtest) => { + const pages = await openPages(subtest); for (const [version, page] of Object.entries(pages)) { const query = chained(32000); // 18.1.5 reuses an instance after a host overflow. Measure recovery from From e08eb431d4df1c596faddcec50b54beed9da9cf8 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Thu, 26 Nov 2026 07:49:24 +0000 Subject: [PATCH 09/13] test(v18): bound the normalization probe by the grammar limit --- versions/18/test/wasm-depth.browser.test.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/versions/18/test/wasm-depth.browser.test.js b/versions/18/test/wasm-depth.browser.test.js index 576a55a0..07c0b4ad 100644 --- a/versions/18/test/wasm-depth.browser.test.js +++ b/versions/18/test/wasm-depth.browser.test.js @@ -17,7 +17,8 @@ const cases = [ ['Nested function calls', 'parseSync', calls, 2000, 10000], ...Object.entries(blocks).map(([name, sql]) => [name, 'parsePlPgSQLSync', sql, 1000, 10000]), ['Normalize operators', 'normalizeSync', chained, 100, 32000], - ['Normalize subqueries', 'normalizeSync', subqueries, 100, 10000], + // PostgreSQL's grammar caps nested subqueries at just over 3300. + ['Normalize subqueries', 'normalizeSync', subqueries, 100, 3400], ]; async function bundleParser(dir) { From d440c84d77223ef8061c22235d66054d54129fb1 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Thu, 26 Nov 2026 07:50:16 +0000 Subject: [PATCH 10/13] test(v18): allow only the verified PL/pgSQL result changes --- versions/18/release-diff.allow.json | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/versions/18/release-diff.allow.json b/versions/18/release-diff.allow.json index 2763311e..c24e991c 100644 --- a/versions/18/release-diff.allow.json +++ b/versions/18/release-diff.allow.json @@ -1,21 +1,30 @@ { "allow": [ { - "id": "edge:plpgsql-if-blocks-*:parsePlPgSQL", + "id": [ + "edge:plpgsql-if-blocks-5000:parsePlPgSQL", + "edge:plpgsql-if-blocks-10000:parsePlPgSQL" + ], "baseline": "18.2.7", "published": "Error: memory exhausted at or near \"THEN\"", "candidate": "SqlError: memory exhausted at or near \"THEN\"", "reason": "The PostgreSQL grammar limit is reported as a SqlError with its existing diagnostic" }, { - "id": "edge:plpgsql-begin-blocks-*:parsePlPgSQL", + "id": [ + "edge:plpgsql-begin-blocks-5000:parsePlPgSQL", + "edge:plpgsql-begin-blocks-10000:parsePlPgSQL" + ], "baseline": "18.2.7", "published": "Error: memory exhausted at or near \"BEGIN\"", "candidate": "SqlError: memory exhausted at or near \"BEGIN\"", "reason": "The PostgreSQL grammar limit is reported as a SqlError with its existing diagnostic" }, { - "id": "edge:plpgsql-loops-*:parsePlPgSQL", + "id": [ + "edge:plpgsql-loops-5000:parsePlPgSQL", + "edge:plpgsql-loops-10000:parsePlPgSQL" + ], "baseline": "18.2.7", "published": "Error: memory exhausted at or near \"LOOP\"", "candidate": "SqlError: memory exhausted at or near \"LOOP\"", From 82a713ebfe7299cd3416016dac56e1082ca72503 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Thu, 26 Nov 2026 08:00:35 +0000 Subject: [PATCH 11/13] test(v18): decouple tiering warmup from browser tab timers --- versions/18/test/wasm-depth.browser.test.js | 39 +++++++++++++++------ 1 file changed, 28 insertions(+), 11 deletions(-) diff --git a/versions/18/test/wasm-depth.browser.test.js b/versions/18/test/wasm-depth.browser.test.js index 07c0b4ad..b8867d73 100644 --- a/versions/18/test/wasm-depth.browser.test.js +++ b/versions/18/test/wasm-depth.browser.test.js @@ -2,6 +2,7 @@ const { test } = require('node:test'); const assert = require('node:assert/strict'); const path = require('node:path'); const { appendFileSync } = require('node:fs'); +const { setTimeout: delay } = require('node:timers/promises'); const { build } = require('esbuild-wasm'); const { firefox, webkit } = require('playwright'); const { chained, subqueries, calls, blocks } = require('./wasm-depth-cases'); @@ -33,7 +34,7 @@ async function bundleParser(dir) { return outputFiles[0].text; } -async function openParser(browser, dir, script) { +async function openParser(browser, version, dir, script) { const page = await browser.newPage(); const origin = 'http://libpg-query.test'; await page.route(origin + '/**', (route) => { @@ -46,23 +47,38 @@ async function openParser(browser, dir, script) { default: return route.abort(); } }); - await page.goto(origin); + await page.goto(origin + '/?build=' + version); return page; } -async function probe(page, { method, query, expectedParameters, fresh = false, warmup }) { +async function probe(page, { method, query, expectedParameters, fresh = false, warmup, depth }) { if (fresh) await page.reload(); - return page.evaluate(async ({ method, query, expectedParameters, warmup }) => { + const label = `${page.url()} ${method} depth=${depth ?? 'recovery'}`; + const slow = setTimeout(() => console.log(`Slow browser probe: ${label}`), 15000); + try { + if (fresh || warmup) { + await page.evaluate(async ({ method, warmup }) => { + globalThis.parser ??= await import('/parser.js'); + await globalThis.parser.loadModule(); + if (warmup) for (let i = 0; i < 20; i++) globalThis.parser[method](warmup); + }, { method, warmup }); + // Give the engine time to finish background compilation without relying + // on timers in a potentially backgrounded browser tab. + if (warmup) await delay(20); + } + return await evaluateQuery(page, { method, query, expectedParameters }); + } finally { + clearTimeout(slow); + } +} + +async function evaluateQuery(page, { method, query, expectedParameters }) { + return page.evaluate(async ({ method, query, expectedParameters }) => { if (!globalThis.parser) { globalThis.parser = await import('/parser.js'); await globalThis.parser.loadModule(); } const lib = globalThis.parser; - if (warmup) { - for (let i = 0; i < 20; i++) lib[method](warmup); - // WebKit can finish compiling a new tier while the probe is running. - await new Promise(resolve => setTimeout(resolve, 20)); - } let error = null; let result; try { @@ -88,7 +104,7 @@ async function probe(page, { method, query, expectedParameters, fresh = false, w function assertRecovered(result) { if (result.stmts.length !== 1) throw new Error('Parser did not recover'); } - }, { method, query, expectedParameters, warmup }); + }, { method, query, expectedParameters }); } const grammarLimit = /^memory exhausted at or near /; @@ -110,6 +126,7 @@ function assertLimit(error, version, name, publishedError) { async function measure(page, version, name, method, sql, floor, ceiling) { const tryDepth = (depth, warmup) => probe(page, { + depth, method, query: sql(depth), expectedParameters: sql === chained ? depth + 1 : 1, @@ -151,7 +168,7 @@ for (const [name, engine] of Object.entries(engines)) { [version, dir, await bundleParser(dir)])); const openPages = async (subtest) => Object.fromEntries(await Promise.all( bundles.map(async ([version, dir, script]) => { - const page = await openParser(browser, dir, script); + const page = await openParser(browser, version, dir, script); subtest.after(() => page.context().close()); return [version, page]; }) From 74853877373a17f2bef1180f7fb1b801dea06b5a Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Thu, 26 Nov 2026 08:10:44 +0000 Subject: [PATCH 12/13] test(v18): budget for published normalization probes on macOS --- versions/18/test/wasm-depth.browser.test.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/versions/18/test/wasm-depth.browser.test.js b/versions/18/test/wasm-depth.browser.test.js index b8867d73..ea046c21 100644 --- a/versions/18/test/wasm-depth.browser.test.js +++ b/versions/18/test/wasm-depth.browser.test.js @@ -161,7 +161,9 @@ if (selected && !Object.hasOwn(engines, selected)) throw new Error(`Unknown brow for (const [name, engine] of Object.entries(engines)) { if (selected && name !== selected) continue; - test(name, { timeout: 360000 }, async (t) => { + // The published normalizer's subquery probes can each take over 15s on + // macOS WebKit. Leave time for those probes without relaxing their checks. + test(name, { timeout: 600000 }, async (t) => { const browser = await engine.launch(); t.after(() => browser.close()); const bundles = await Promise.all(Object.entries(builds).map(async ([version, dir]) => From 9587bf465ace6d7b70c371e9d2e4d52a89a3e65b Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Thu, 26 Nov 2026 08:55:58 +0000 Subject: [PATCH 13/13] test(v18): check every browser depth diagnostic and prove host recovery --- .github/workflows/ci.yml | 7 ++- versions/18/test/wasm-depth.browser.test.js | 63 ++++++++++++--------- 2 files changed, 40 insertions(+), 30 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 338b2fba..4de400c6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -138,7 +138,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: - node-version: '20.x' + node-version: '22.x' - uses: pnpm/action-setup@v2 with: version: 8.15.1 @@ -147,7 +147,10 @@ jobs: with: name: wasm-artifacts-v18 path: versions/18/wasm/ - - run: pnpm --dir versions/18 exec playwright install --with-deps "$WASM_TEST_BROWSER" + - if: runner.os == 'Linux' + run: pnpm --dir versions/18 exec playwright install --with-deps "$WASM_TEST_BROWSER" + - if: runner.os == 'macOS' + run: pnpm --dir versions/18 exec playwright install "$WASM_TEST_BROWSER" - run: pnpm --dir versions/18 test:browser build-parser: diff --git a/versions/18/test/wasm-depth.browser.test.js b/versions/18/test/wasm-depth.browser.test.js index ea046c21..bcba2b86 100644 --- a/versions/18/test/wasm-depth.browser.test.js +++ b/versions/18/test/wasm-depth.browser.test.js @@ -84,7 +84,7 @@ async function evaluateQuery(page, { method, query, expectedParameters }) { try { result = await lib[method](query); } catch (e) { - error = { name: e.name, message: e.message, sqlError: e instanceof lib.SqlError }; + error = { message: e.message, sqlError: e instanceof lib.SqlError, cause: e.cause?.message }; } assertRecovered(lib.parseSync('SELECT 1')); assertRecovered(await lib.parse('SELECT 1')); @@ -124,7 +124,7 @@ function assertLimit(error, version, name, publishedError) { } } -async function measure(page, version, name, method, sql, floor, ceiling) { +async function measure(page, version, name, method, sql, floor, ceiling, checkLimit) { const tryDepth = (depth, warmup) => probe(page, { depth, method, @@ -141,18 +141,17 @@ async function measure(page, version, name, method, sql, floor, ceiling) { let high = ceiling / depthStep; const warmup = sql(floor); const limit = await tryDepth(ceiling, warmup); - let error = limit; - assert.ok(limit, `${version}: ${name} exceeded the depth search ceiling ${ceiling}`); + await checkLimit(limit, ceiling); while (high - low > 1) { const mid = Math.floor((low + high) / 2); const result = await tryDepth(mid * depthStep, warmup); if (!result) low = mid; else { - error = result; + await checkLimit(result, mid * depthStep); high = mid; } } - return { depth: low * depthStep, error, limit }; + return { depth: low * depthStep, limit }; } const engines = { firefox, webkit }; @@ -181,29 +180,35 @@ for (const [name, engine] of Object.entries(engines)) { // Don't retain browser resources from earlier searches. Each search // reloads the page and instantiates a fresh WASM heap for each probe. const pages = await openPages(subtest); - const run = version => measure(pages[version], version, label, method, sql, floor, ceiling); - let published = await run(baseline); - let candidate = await run('candidate'); - if (candidate.depth < published.depth - depthStep) { - // A single measurement can straddle WebKit's concurrent WASM tier-up. - // Require the loss to reproduce in the median of three searches. - const median = results => results.sort((a, b) => a.depth - b.depth)[1]; - published = median([published, await run(baseline), await run(baseline)]); - candidate = median([candidate, await run('candidate'), await run('candidate')]); + let published, candidate, publishedGrammar; + const run = version => measure( + pages[version], version, label, method, sql, floor, ceiling, + async (error, depth) => { + let diagnostic = published?.limit; + if (version === 'candidate' && method === 'normalizeSync' && + grammarLimit.test(error?.message) && !grammarLimit.test(diagnostic?.message)) { + // The old normalizer may overflow before the underlying SQL grammar does. + publishedGrammar ??= probe(pages[baseline], { + method: 'parseSync', query: sql(ceiling), fresh: true, + }); + diagnostic = await publishedGrammar; + } + assertLimit(error, version, `${label} at depth ${depth}`, diagnostic); + }, + ); + try { + published = await run(baseline); + candidate = await run('candidate'); + if (candidate.depth < published.depth - depthStep) { + // A single measurement can straddle WebKit's concurrent WASM tier-up. + // Require the loss to reproduce in the median of three searches. + const median = results => results.sort((a, b) => a.depth - b.depth)[1]; + published = median([published, await run(baseline), await run(baseline)]); + candidate = median([candidate, await run('candidate'), await run('candidate')]); + } + } finally { + rows.push(`| ${label} | ${published?.depth ?? 'not measured'} | ${candidate?.depth ?? 'not measured'} |`); } - rows.push(`| ${label} | ${published.depth} | ${candidate.depth} |`); - assertLimit(published.error, baseline, label); - assertLimit(published.limit, baseline, label); - let publishedDiagnostic = published.limit; - if (method === 'normalizeSync' && grammarLimit.test(candidate.limit.message) && - !grammarLimit.test(publishedDiagnostic.message)) { - // The old normalizer may overflow before the underlying SQL grammar does. - publishedDiagnostic = await probe(pages[baseline], { - method: 'parseSync', query: sql(ceiling), fresh: true, - }); - } - assertLimit(candidate.error, 'candidate', label, publishedDiagnostic); - assertLimit(candidate.limit, 'candidate', label, publishedDiagnostic); assert.ok(candidate.depth >= published.depth - depthStep, `${label}: depth fell from ${published.depth} to ${candidate.depth}`); if (method === 'normalizeSync') { @@ -214,6 +219,8 @@ for (const [name, engine] of Object.entries(engines)) { // host overflow after warming the code, then exercise the replacement. const overflow = await probe(page, { method: 'parseSync', query: chained(32000) }); assertLimit(overflow, 'candidate', label); + assert.match(overflow.cause ?? '', /call stack|too much recursion/i, + `${label}: expected a translated host stack overflow`); const depth = Math.max(floor, published.depth - depthStep); const afterOverflow = await probe(page, { method, query: sql(depth), expectedParameters: sql === chained ? depth + 1 : 1,