diff --git a/templates/full/index.ts b/templates/full/index.ts index 9e254ce..baff522 100644 --- a/templates/full/index.ts +++ b/templates/full/index.ts @@ -198,7 +198,22 @@ function invalidateModule(error: unknown): void { wasmModule = undefined; } -// An exception out of a WASM call (V8 stack overflow on deeply nested SQL, a +// The host engine's native stack (V8 and JSC: RangeError, Firefox: +// InternalError) can run out inside a WASM call before libpg_query's own +// stack depth check, which only measures the WASM stack. +function isStackOverflow(error: Error): boolean { + return (error instanceof RangeError && /call stack/i.test(error.message)) + || (error.name === 'InternalError' && /too much recursion/i.test(error.message)); +} + +function stackDepthError(cause: Error): SqlError { + const message = 'stack depth limit exceeded'; + // Until its stack is formatted, the error's WASM frames keep the dropped instance alive. + void cause.stack; + return Object.assign(new SqlError(message, { message, cursorPosition: 0 }), { cause }); +} + +// An exception out of a WASM call (host stack overflow on deeply nested SQL, a // trap, or exit() once the heap limit is hit) skips libpg_query's cleanup and // leaves the instance corrupt, so replace it with a fresh one. function callWasm(fn: () => number): number { @@ -210,6 +225,7 @@ function callWasm(fn: () => number): number { if (proc) proc.exitCode = exitCode; if (error instanceof Error) { invalidateModule(error); + if (isStackOverflow(error)) throw stackDepthError(error); throw error; } const reason = typeof error === 'object' && error !== null diff --git a/versions/18/Makefile b/versions/18/Makefile index 4197615..1674ee4 100644 --- a/versions/18/Makefile +++ b/versions/18/Makefile @@ -19,7 +19,7 @@ WASM_STACK_SIZE ?= 33554432 # byte-for-byte. Set in package.json `x-publish` and applied by copy:templates. LIBPG_QUERY_REPO := https://github.com/constructive-io/libpg_query.git LIBPG_QUERY_TAG := 18-constructive -LIBPG_QUERY_COMMIT := 7791971be1fc169d3f1b0d1ec887dc3f134ad134 +LIBPG_QUERY_COMMIT := f9f1b676f629a831bd2c5f7b34a2dc41d9cdf967 CACHE_DIR := .cache diff --git a/versions/18/package.json b/versions/18/package.json index c10b4bf..8601dc3 100644 --- a/versions/18/package.json +++ b/versions/18/package.json @@ -15,7 +15,7 @@ "distTag": "pg18", "libpgQueryRepo": "https://github.com/constructive-io/libpg_query.git", "libpgQueryTag": "18-constructive", - "libpgQueryCommit": "7791971be1fc169d3f1b0d1ec887dc3f134ad134", + "libpgQueryCommit": "f9f1b676f629a831bd2c5f7b34a2dc41d9cdf967", "fullApi": true }, "files": [ diff --git a/versions/18/release-diff.allow.json b/versions/18/release-diff.allow.json index 6c1ea86..20d8b73 100644 --- a/versions/18/release-diff.allow.json +++ b/versions/18/release-diff.allow.json @@ -1,3 +1,45 @@ { - "allow": [] + "allow": [ + { + "id": [ + "edge:*:parse", + "edge:*:normalize", + "edge:*:fingerprint" + ], + "baseline": "18.2.7", + "published": "stack depth limit exceeded", + "candidate": "ok", + "reason": "18.2.7 capped the stack depth check at 512 kB of the WASM stack; the check now uses the whole stack, so deep SQL parses again as in 18.1.5" + }, + { + "id": [ + "edge:*:parse", + "edge:*:scan" + ], + "baseline": "18.2.7", + "published": "stack depth limit exceeded", + "candidate": "RangeError: Maximum call stack size exceeded", + "reason": "Same change: the candidate parses these now, and the RangeError is this script's JSON.stringify overflowing on the very deep parse tree" + }, + { + "id": "edge:plpgsql-*:parsePlPgSQL", + "baseline": "18.2.7", + "published": "Error: stack depth limit exceeded", + "candidate": "ok", + "reason": "The 512 kB cap stopped PL/pgSQL at about 350 nested blocks; without it they parse again as in 18.1.5" + }, + { + "id": [ + "edge:*:parse", + "edge:*:normalize", + "edge:*:fingerprint", + "edge:*:scan", + "edge:plpgsql-*:parsePlPgSQL" + ], + "baseline": "18.2.7", + "published": "RangeError: Maximum call stack size exceeded", + "candidate": "stack depth limit exceeded", + "reason": "A host stack overflow inside the parser or JSON.parse is now reported as a stack depth error instead of a raw RangeError" + } + ] } diff --git a/versions/18/src/index.ts b/versions/18/src/index.ts index 5c2a9a1..f646d9e 100644 --- a/versions/18/src/index.ts +++ b/versions/18/src/index.ts @@ -205,7 +205,22 @@ function invalidateModule(error: unknown): void { wasmModule = undefined; } -// An exception out of a WASM call (V8 stack overflow on deeply nested SQL, a +// The host engine's native stack (V8 and JSC: RangeError, Firefox: +// InternalError) can run out inside a WASM call before libpg_query's own +// stack depth check, which only measures the WASM stack. +function isStackOverflow(error: Error): boolean { + return (error instanceof RangeError && /call stack/i.test(error.message)) + || (error.name === 'InternalError' && /too much recursion/i.test(error.message)); +} + +function stackDepthError(cause: Error): SqlError { + const message = 'stack depth limit exceeded'; + // Until its stack is formatted, the error's WASM frames keep the dropped instance alive. + void cause.stack; + return Object.assign(new SqlError(message, { message, cursorPosition: 0 }), { cause }); +} + +// An exception out of a WASM call (host stack overflow on deeply nested SQL, a // trap, or exit() once the heap limit is hit) skips libpg_query's cleanup and // leaves the instance corrupt, so replace it with a fresh one. function callWasm(fn: () => number): number { @@ -217,6 +232,7 @@ function callWasm(fn: () => number): number { if (proc) proc.exitCode = exitCode; if (error instanceof Error) { invalidateModule(error); + if (isStackOverflow(error)) throw stackDepthError(error); throw error; } const reason = typeof error === 'object' && error !== null diff --git a/versions/18/test/wasm-recovery.test.js b/versions/18/test/wasm-recovery.test.js index 5f50a19..e03f7bb 100644 --- a/versions/18/test/wasm-recovery.test.js +++ b/versions/18/test/wasm-recovery.test.js @@ -45,6 +45,47 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { } }); + // 18.1.5 parsed these; 18.2.7's 512kB WASM limit rejected them. + it('parses nesting that 18.1.5 parsed', async () => { + await loadModule(); + // Nested subqueries and function calls overflow V8's stack on macOS near the old limit. + const chained = 'SELECT 1' + '+1'.repeat(4000); + assert.doesNotThrow(() => assert.equal(parseSync(chained).stmts.length, 1), 'chained operators'); + const blocks = { + 'nested IF blocks': ['IF true THEN ', 'NULL;', ' END IF;'], + 'nested BEGIN blocks': ['BEGIN ', 'NULL;', ' END;'], + 'nested loops': ['LOOP ', 'EXIT;', ' END LOOP;'], + }; + for (const [name, [open, body, close]] of Object.entries(blocks)) { + const sql = 'CREATE FUNCTION f() RETURNS void LANGUAGE plpgsql AS $$ BEGIN ' + + open.repeat(1000) + body + close.repeat(1000) + ' END $$'; + assert.doesNotThrow(() => assert.equal(lib.parsePlPgSQLSync(sql).plpgsql_funcs.length, 1), name); + } + }); + + // V8's native stack can run out inside a WASM call before libpg_query's own + // check, e.g. in normalize, whose frames are larger there. + it('reports a stack depth error, not a RangeError, for nesting too deep to parse', async () => { + await loadModule(); + const subqueries = (n) => 'SELECT ' + '(SELECT '.repeat(n) + '1' + ')'.repeat(n); + const tooDeep = [ + ['parseSync', DEEP], + ['parseSync', subqueries(3000)], + ['normalizeSync', DEEP], + ['normalizeSync', subqueries(1000)], + ]; + for (const [name, sql] of tooDeep) { + assert.throws(() => lib[name](sql), (error) => { + assert.ok(error instanceof lib.SqlError, `${name}: ${error}`); + assert.equal(error.message, 'stack depth limit exceeded'); + return true; + }); + assert.equal(parseSync('SELECT 1').stmts.length, 1); + } + await assert.rejects(lib.normalize(DEEP), lib.SqlError); + assert.equal((await parse('SELECT 1')).stmts.length, 1); + }); + it('frees replaced WASM heaps even when callers keep the errors', () => { const script = `const lib = require(${JSON.stringify(require.resolve('../wasm/index.cjs'))}); (async () => { @@ -53,8 +94,9 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { gc(); gc(); const base = process.memoryUsage().external; const deep = 'SELECT 1' + '+1'.repeat(100000); + const kept = []; for (let i = 0; i < 30; i++) { - try { lib.parseSync(deep); } catch {} + try { lib.parseSync(deep); } catch (error) { kept.push(error); } await lib.loadModule(); } const huge = 'SELECT 1;\\n'.repeat(5000000); @@ -206,7 +248,7 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { }); // Every entry point, with the next WASM call made to throw: a RangeError -// stands for a stack overflow, a non-Error object for Emscripten's ExitStatus. +// stands for a trap or a stack overflow, a non-Error object for Emscripten's ExitStatus. describe('Recovery from a throw in each entry point', { timeout: 120000 }, () => { const PLPGSQL = 'CREATE FUNCTION f() RETURNS int AS $$ BEGIN RETURN 1; END $$ LANGUAGE plpgsql'; const entryPoints = [ @@ -281,7 +323,7 @@ describe('Recovery from a throw in each entry point', { timeout: 120000 }, () => await isolated.loadModule(); const loadsBefore = loads; for (let i = 0; i < 60; i++) { - throwNext = new RangeError('Maximum call stack size exceeded'); + throwNext = new RangeError('WASM trap'); assert.throws(() => isolated.parseSync('SELECT 1'), RangeError); const failed = used; assert.equal(isolated.parseSync('SELECT 1').stmts.length, 1); @@ -292,10 +334,10 @@ describe('Recovery from a throw in each entry point', { timeout: 120000 }, () => it('makes loadModule() and queued calls wait again when a queued call breaks the fresh instance', async () => { await isolated.loadModule(); - throwNext = new RangeError('Maximum call stack size exceeded'); + throwNext = new RangeError('WASM trap'); assert.throws(() => isolated.parseSync('SELECT 1'), RangeError); const failing = isolated.parse('SELECT 1'); - throwNext = new RangeError('Maximum call stack size exceeded'); + throwNext = new RangeError('WASM trap'); const ready = isolated.loadModule(); const after = isolated.parse('SELECT 1'); await assert.rejects(failing, RangeError); @@ -308,10 +350,10 @@ describe('Recovery from a throw in each entry point', { timeout: 120000 }, () => it('makes loadModule() wait again when a call queued ahead of it breaks the fresh instance', async () => { await isolated.loadModule(); - throwNext = new RangeError('Maximum call stack size exceeded'); + throwNext = new RangeError('WASM trap'); assert.throws(() => isolated.parseSync('SELECT 1'), RangeError); const failing = isolated.parse('SELECT 1'); - throwNext = new RangeError('Maximum call stack size exceeded'); + throwNext = new RangeError('WASM trap'); const ready = isolated.loadModule(); await assert.rejects(failing, RangeError); await ready; @@ -342,10 +384,18 @@ describe('Recovery from a throw in each entry point', { timeout: 120000 }, () => const skip = typeof isolated[name] !== 'function' && 'not in this build'; it(`${name}: rethrows the original Error and recovers`, { skip }, async () => { - const thrown = new RangeError('Maximum call stack size exceeded'); + const thrown = new RangeError('WASM trap'); assert.equal(await failOnce(name, query, thrown), thrown); }); + it(`${name}: reports a V8 stack overflow as a stack depth error and recovers`, { skip }, async () => { + const thrown = new RangeError('Maximum call stack size exceeded'); + const caught = await failOnce(name, query, thrown); + assert.ok(caught instanceof isolated.SqlError); + assert.equal(caught.message, 'stack depth limit exceeded'); + assert.equal(caught.cause, thrown); + }); + it(`${name}: wraps a non-Error throw in an Error and recovers`, { skip }, async () => { const thrown = { name: 'ExitStatus', message: 'Program terminated with exit(1)', status: 1 }; const caught = await failOnce(name, query, thrown); @@ -368,7 +418,7 @@ function loadTrapping(failLoad) { if (trapHeapSize === undefined) return parseRaw(...callArgs); if (trapHeapSize) module.HEAPU8 = { length: trapHeapSize }; trapHeapSize = undefined; - throw new RangeError('Maximum call stack size exceeded'); + throw new RangeError('WASM trap'); }; }, failLoad); isolated.trapNext = (heapSize = 0) => { trapHeapSize = heapSize; };