diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7633227..4de400c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -119,6 +119,40 @@ 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 + env: + WASM_TEST_BROWSER: ${{ matrix.browser }} + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '22.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/ + - 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: name: Build Parser Package 📦 needs: build-wasm diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 54079fa..b561c72 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 c7b2cc0..62dc74b 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/templates/full/index.ts b/templates/full/index.ts index baff522..5849b46 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", "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/release-diff.allow.json b/versions/18/release-diff.allow.json index 4e39b06..221bd71 100644 --- a/versions/18/release-diff.allow.json +++ b/versions/18/release-diff.allow.json @@ -1,5 +1,35 @@ { "allow": [ + { + "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-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-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\"", + "reason": "The PostgreSQL grammar limit is reported as a SqlError with its existing diagnostic" + }, { "id": [ "edge:*:parse", diff --git a/versions/18/src/index.ts b/versions/18/src/index.ts index f646d9e..47fd6a3 100644 --- a/versions/18/src/index.ts +++ b/versions/18/src/index.ts @@ -260,6 +260,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; @@ -454,10 +463,7 @@ export const parsePlPgSQL = awaitInit(async (query: string): Promise { 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-cases.js b/versions/18/test/wasm-depth-cases.js new file mode 100644 index 0000000..1dc1014 --- /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 0000000..bcba2b8 --- /dev/null +++ b/versions/18/test/wasm-depth.browser.test.js @@ -0,0 +1,251 @@ +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'); + +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, 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, 32000], + // PostgreSQL's grammar caps nested subqueries at just over 3300. + ['Normalize subqueries', 'normalizeSync', subqueries, 100, 3400], +]; + +async function bundleParser(dir) { + const { outputFiles } = await build({ + entryPoints: [path.join(dir, 'index.js')], + bundle: true, + format: 'esm', + platform: 'browser', + external: ['node:*'], + write: false, + }); + return outputFiles[0].text; +} + +async function openParser(browser, version, 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: script }); + 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 + '/?build=' + version); + return page; +} + +async function probe(page, { method, query, expectedParameters, fresh = false, warmup, depth }) { + if (fresh) await page.reload(); + 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; + let error = null; + let result; + try { + result = await lib[method](query); + } catch (e) { + error = { message: e.message, sqlError: e instanceof lib.SqlError, cause: e.cause?.message }; + } + 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) + : 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'); + } + }, { method, query, expectedParameters }); +} + +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') { + // 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.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, checkLimit) { + const tryDepth = (depth, warmup) => probe(page, { + depth, + method, + query: sql(depth), + expectedParameters: sql === chained ? depth + 1 : 1, + fresh: true, + warmup, + }); + assert.equal(await tryDepth(floor), null, `${version}: ${name} at depth ${floor}`); + + // 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); + const limit = await tryDepth(ceiling, warmup); + 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 { + await checkLimit(result, mid * depthStep); + high = mid; + } + } + return { depth: low * depthStep, limit }; +} + +const engines = { firefox, webkit }; +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)) { + if (selected && name !== selected) continue; + // 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]) => + [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, version, 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 (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); + 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'} |`); + } + assert.ok(candidate.depth >= published.depth - depthStep, + `${label}: depth fell from ${published.depth} to ${candidate.depth}`); + if (method === 'normalizeSync') { + 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); + 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, + }); + assert.equal(afterOverflow, null, `${label}: cannot reach published depth after overflow`); + } + }); + } + 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 (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 + // 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'); + } + }); + }); +}