From b142aeff37f7db60928fc88269cd1014add26dea Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Sun, 22 Nov 2026 03:16:15 +0000 Subject: [PATCH 1/2] feat(v18): build against the upb libpg_query fork (combined PG 18.6 patches) --- templates/full/index.ts | 44 ++++++++++++-------- templates/full/wasm_wrapper.c | 54 +++++++++++------------- versions/18/Makefile | 4 +- versions/18/package.json | 4 +- versions/18/src/index.ts | 44 ++++++++++++-------- versions/18/src/wasm_wrapper.c | 54 +++++++++++------------- versions/18/test/pg18.test.js | 6 +-- versions/18/test/wasm-recovery.test.js | 57 ++++++++++++++++---------- 8 files changed, 145 insertions(+), 122 deletions(-) diff --git a/templates/full/index.ts b/templates/full/index.ts index 66c02098..1caa6833 100644 --- a/templates/full/index.ts +++ b/templates/full/index.ts @@ -211,6 +211,22 @@ function callWasm(fn: () => number): number { } } +// libpg_query reports a failed allocation as a plain "out of memory" error and +// keeps going, but the instance's heap stays grown to the size it reached (WASM +// memory never shrinks), so load a fresh instance and let this one be freed. +function outOfMemoryError(): Error { + stale = true; + instantiate(); + return new Error('libpg_query ran out of WASM memory (heap limit is WASM_MAXIMUM_MEMORY, 1 GiB); parse large inputs in smaller pieces'); +} + +function throwIfErrorString(resultStr: string): void { + if (resultStr === 'out of memory') throw outOfMemoryError(); + if (resultStr.startsWith('syntax error') || resultStr.startsWith('deparse error') || resultStr.startsWith('ERROR') || resultStr.startsWith('stack depth limit exceeded')) { + throw new Error(resultStr); + } +} + function ensureLoaded() { if (!wasmModule) throw new Error("WASM module not initialized. Call `loadModule()` first."); } @@ -321,6 +337,7 @@ export const parse = awaitInit(async (query: string): Promise => { const funcname = funcnamePtr ? wasmModule.UTF8ToString(funcnamePtr) : undefined; const filename = filenamePtr ? wasmModule.UTF8ToString(filenamePtr) : undefined; + if (message === 'out of memory') throw outOfMemoryError(); throw new SqlError(message, { message, cursorPosition: cursorpos > 0 ? cursorpos - 1 : 0, // Convert to 0-based @@ -357,6 +374,7 @@ export const parsePlPgSQL = awaitInit(async (query: string): Promise => { resultPtr = callWasm(() => wasmModule._wasm_fingerprint(queryPtr)); const resultStr = ptrToString(resultPtr); - if (resultStr.startsWith('syntax error') || resultStr.startsWith('deparse error') || resultStr.startsWith('ERROR')) { - throw new Error(resultStr); - } + throwIfErrorString(resultStr); return resultStr; } finally { @@ -404,9 +420,7 @@ export const normalize = awaitInit(async (query: string): Promise => { resultPtr = callWasm(() => wasmModule._wasm_normalize_query(queryPtr)); const resultStr = ptrToString(resultPtr); - if (resultStr.startsWith('syntax error') || resultStr.startsWith('deparse error') || resultStr.startsWith('ERROR')) { - throw new Error(resultStr); - } + throwIfErrorString(resultStr); return resultStr; } finally { @@ -461,6 +475,7 @@ export function parseSync(query: string): ParseResult { const funcname = funcnamePtr ? wasmModule.UTF8ToString(funcnamePtr) : undefined; const filename = filenamePtr ? wasmModule.UTF8ToString(filenamePtr) : undefined; + if (message === 'out of memory') throw outOfMemoryError(); throw new SqlError(message, { message, cursorPosition: cursorpos > 0 ? cursorpos - 1 : 0, // Convert to 0-based @@ -500,6 +515,7 @@ export function parsePlPgSQLSync(query: string): ParseResult { // Success is always a JSON object; anything else is an error message if (!resultStr.startsWith('{')) { + if (resultStr === 'out of memory') throw outOfMemoryError(); throw new Error(resultStr); } @@ -526,9 +542,7 @@ export function fingerprintSync(query: string): string { resultPtr = callWasm(() => wasmModule._wasm_fingerprint(queryPtr)); const resultStr = ptrToString(resultPtr); - if (resultStr.startsWith('syntax error') || resultStr.startsWith('deparse error') || resultStr.startsWith('ERROR')) { - throw new Error(resultStr); - } + throwIfErrorString(resultStr); return resultStr; } finally { @@ -553,9 +567,7 @@ export function normalizeSync(query: string): string { resultPtr = callWasm(() => wasmModule._wasm_normalize_query(queryPtr)); const resultStr = ptrToString(resultPtr); - if (resultStr.startsWith('syntax error') || resultStr.startsWith('deparse error') || resultStr.startsWith('ERROR')) { - throw new Error(resultStr); - } + throwIfErrorString(resultStr); return resultStr; } finally { @@ -577,9 +589,7 @@ export const scan = awaitInit(async (query: string): Promise => { resultPtr = callWasm(() => wasmModule._wasm_scan(queryPtr)); const resultStr = ptrToString(resultPtr); - if (resultStr.startsWith('syntax error') || resultStr.startsWith('deparse error') || resultStr.startsWith('ERROR')) { - throw new Error(resultStr); - } + throwIfErrorString(resultStr); return JSON.parse(resultStr); } finally { @@ -604,9 +614,7 @@ export function scanSync(query: string): ScanResult { resultPtr = callWasm(() => wasmModule._wasm_scan(queryPtr)); const resultStr = ptrToString(resultPtr); - if (resultStr.startsWith('syntax error') || resultStr.startsWith('deparse error') || resultStr.startsWith('ERROR')) { - throw new Error(resultStr); - } + throwIfErrorString(resultStr); return JSON.parse(resultStr); } finally { diff --git a/templates/full/wasm_wrapper.c b/templates/full/wasm_wrapper.c index 268d2893..4d726ef8 100644 --- a/templates/full/wasm_wrapper.c +++ b/templates/full/wasm_wrapper.c @@ -1,6 +1,6 @@ #include "pg_query.h" -#include "protobuf/pg_query.pb-c.h" #include +#include #include #include #include @@ -230,7 +230,7 @@ void wasm_free_detailed_result(WasmDetailedResult* result) { } } -static const char* get_token_name(PgQuery__Token token_type) { +static const char* get_token_name(PgQueryToken token_type) { // Map some common token types to readable names // Note: This is a simplified mapping - full enum lookup would require more complexity switch(token_type) { @@ -255,7 +255,7 @@ static const char* get_token_name(PgQuery__Token token_type) { } } -static const char* get_keyword_name(PgQuery__KeywordKind keyword_kind) { +static const char* get_keyword_name(PgQueryKeywordKind keyword_kind) { switch(keyword_kind) { case 0: return "NO_KEYWORD"; case 1: return "UNRESERVED_KEYWORD"; @@ -266,7 +266,7 @@ static const char* get_keyword_name(PgQuery__KeywordKind keyword_kind) { } } -static char* build_scan_json(PgQuery__ScanResult *scan_result, const char* original_sql) { +static char* build_scan_json(const PgQueryScanTokensResult *scan_result, const char* original_sql) { if (!scan_result || !original_sql) { return safe_strdup("{\"version\":0,\"tokens\":[]}"); } @@ -275,29 +275,36 @@ static char* build_scan_json(PgQuery__ScanResult *scan_result, const char* origi // contributes at most ~170 bytes of fixed JSON plus up to 2 bytes per input // byte once escaped. size_t estimated_size = 1024; - for (size_t i = 0; i < scan_result->n_tokens; i++) { - PgQuery__ScanToken *token = scan_result->tokens[i]; + for (int i = 0; i < scan_result->n_tokens; i++) { + const PgQueryScanToken *token = &scan_result->tokens[i]; int token_length = token->end - token->start; if (token_length < 0) token_length = 0; - estimated_size += (size_t) token_length * 2 + 200; + size_t token_size = (size_t) token_length * 2 + 200; + if (estimated_size > SIZE_MAX - token_size) { + return safe_strdup("out of memory"); + } + estimated_size += token_size; } char* json = safe_malloc(estimated_size); if (!json) { - return safe_strdup("{\"version\":0,\"tokens\":[]}"); + return safe_strdup("out of memory"); } // Start building JSON - size_t pos = snprintf(json, estimated_size, "{\"version\":%d,\"tokens\":[", scan_result->version); + size_t pos = snprintf(json, estimated_size, "{\"version\":%d,\"tokens\":[", PG_VERSION_NUM); - for (size_t i = 0; i < scan_result->n_tokens; i++) { - PgQuery__ScanToken *token = scan_result->tokens[i]; + for (int i = 0; i < scan_result->n_tokens; i++) { + const PgQueryScanToken *token = &scan_result->tokens[i]; // Extract token text from original SQL int token_length = token->end - token->start; if (token_length < 0) token_length = 0; // Safety check char* token_text = safe_malloc(token_length + 1); - if (!token_text) continue; + if (!token_text) { + free(json); + return safe_strdup("out of memory"); + } if (token_length > 0) { strncpy(token_text, &original_sql[token->start], token_length); @@ -308,7 +315,8 @@ static char* build_scan_json(PgQuery__ScanResult *scan_result, const char* origi char* escaped_text = safe_malloc(token_length * 2 + 1); if (!escaped_text) { free(token_text); - continue; + free(json); + return safe_strdup("out of memory"); } int escaped_pos = 0; @@ -369,29 +377,17 @@ char* wasm_scan(const char* input) { return safe_strdup("Invalid input: query cannot be null or empty"); } - PgQueryScanResult result = pg_query_scan(input); + PgQueryScanTokensResult result = pg_query_scan_tokens(input); if (result.error) { char* error_msg = safe_strdup(result.error->message); - pg_query_free_scan_result(result); + pg_query_free_scan_tokens_result(result); return error_msg ? error_msg : safe_strdup("Memory allocation failed"); } - // Unpack protobuf data - PgQuery__ScanResult *scan_result = pg_query__scan_result__unpack( - NULL, result.pbuf.len, (void *) result.pbuf.data); - - if (!scan_result) { - pg_query_free_scan_result(result); - return safe_strdup("Failed to unpack scan result"); - } - - // Convert to JSON - char* json_result = build_scan_json(scan_result, input); + char* json_result = build_scan_json(&result, input); - // Clean up - pg_query__scan_result__free_unpacked(scan_result, NULL); - pg_query_free_scan_result(result); + pg_query_free_scan_tokens_result(result); return json_result ? json_result : safe_strdup("{\"version\":0,\"tokens\":[]}"); } diff --git a/versions/18/Makefile b/versions/18/Makefile index 19bcc664..69ffe818 100644 --- a/versions/18/Makefile +++ b/versions/18/Makefile @@ -18,8 +18,8 @@ WASM_STACK_SIZE ?= 33554432 # libpg_query source, pinned to an exact commit so a release can be rebuilt # 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 := b0f5f331dc50d69597ec610de7b21afa47a66808 +LIBPG_QUERY_TAG := feat/pg18-combined-patches +LIBPG_QUERY_COMMIT := 0832f810aa38fb06358c761d0b1b246f337e9333 CACHE_DIR := .cache diff --git a/versions/18/package.json b/versions/18/package.json index 94c0d160..d976c98b 100644 --- a/versions/18/package.json +++ b/versions/18/package.json @@ -14,8 +14,8 @@ "pgVersion": "18", "distTag": "pg18", "libpgQueryRepo": "https://github.com/constructive-io/libpg_query.git", - "libpgQueryTag": "18-constructive", - "libpgQueryCommit": "b0f5f331dc50d69597ec610de7b21afa47a66808", + "libpgQueryTag": "feat/pg18-combined-patches", + "libpgQueryCommit": "0832f810aa38fb06358c761d0b1b246f337e9333", "fullApi": true }, "files": [ diff --git a/versions/18/src/index.ts b/versions/18/src/index.ts index 24751075..5082f7f9 100644 --- a/versions/18/src/index.ts +++ b/versions/18/src/index.ts @@ -218,6 +218,22 @@ function callWasm(fn: () => number): number { } } +// libpg_query reports a failed allocation as a plain "out of memory" error and +// keeps going, but the instance's heap stays grown to the size it reached (WASM +// memory never shrinks), so load a fresh instance and let this one be freed. +function outOfMemoryError(): Error { + stale = true; + instantiate(); + return new Error('libpg_query ran out of WASM memory (heap limit is WASM_MAXIMUM_MEMORY, 1 GiB); parse large inputs in smaller pieces'); +} + +function throwIfErrorString(resultStr: string): void { + if (resultStr === 'out of memory') throw outOfMemoryError(); + if (resultStr.startsWith('syntax error') || resultStr.startsWith('deparse error') || resultStr.startsWith('ERROR') || resultStr.startsWith('stack depth limit exceeded')) { + throw new Error(resultStr); + } +} + function ensureLoaded() { if (!wasmModule) throw new Error("WASM module not initialized. Call `loadModule()` first."); } @@ -328,6 +344,7 @@ export const parse = awaitInit(async (query: string): Promise => { const funcname = funcnamePtr ? wasmModule.UTF8ToString(funcnamePtr) : undefined; const filename = filenamePtr ? wasmModule.UTF8ToString(filenamePtr) : undefined; + if (message === 'out of memory') throw outOfMemoryError(); throw new SqlError(message, { message, cursorPosition: cursorpos > 0 ? cursorpos - 1 : 0, // Convert to 0-based @@ -364,6 +381,7 @@ export const parsePlPgSQL = awaitInit(async (query: string): Promise => { resultPtr = callWasm(() => wasmModule._wasm_fingerprint(queryPtr)); const resultStr = ptrToString(resultPtr); - if (resultStr.startsWith('syntax error') || resultStr.startsWith('deparse error') || resultStr.startsWith('ERROR')) { - throw new Error(resultStr); - } + throwIfErrorString(resultStr); return resultStr; } finally { @@ -411,9 +427,7 @@ export const normalize = awaitInit(async (query: string): Promise => { resultPtr = callWasm(() => wasmModule._wasm_normalize_query(queryPtr)); const resultStr = ptrToString(resultPtr); - if (resultStr.startsWith('syntax error') || resultStr.startsWith('deparse error') || resultStr.startsWith('ERROR')) { - throw new Error(resultStr); - } + throwIfErrorString(resultStr); return resultStr; } finally { @@ -468,6 +482,7 @@ export function parseSync(query: string): ParseResult { const funcname = funcnamePtr ? wasmModule.UTF8ToString(funcnamePtr) : undefined; const filename = filenamePtr ? wasmModule.UTF8ToString(filenamePtr) : undefined; + if (message === 'out of memory') throw outOfMemoryError(); throw new SqlError(message, { message, cursorPosition: cursorpos > 0 ? cursorpos - 1 : 0, // Convert to 0-based @@ -507,6 +522,7 @@ export function parsePlPgSQLSync(query: string): ParseResult { // Success is always a JSON object; anything else is an error message if (!resultStr.startsWith('{')) { + if (resultStr === 'out of memory') throw outOfMemoryError(); throw new Error(resultStr); } @@ -533,9 +549,7 @@ export function fingerprintSync(query: string): string { resultPtr = callWasm(() => wasmModule._wasm_fingerprint(queryPtr)); const resultStr = ptrToString(resultPtr); - if (resultStr.startsWith('syntax error') || resultStr.startsWith('deparse error') || resultStr.startsWith('ERROR')) { - throw new Error(resultStr); - } + throwIfErrorString(resultStr); return resultStr; } finally { @@ -560,9 +574,7 @@ export function normalizeSync(query: string): string { resultPtr = callWasm(() => wasmModule._wasm_normalize_query(queryPtr)); const resultStr = ptrToString(resultPtr); - if (resultStr.startsWith('syntax error') || resultStr.startsWith('deparse error') || resultStr.startsWith('ERROR')) { - throw new Error(resultStr); - } + throwIfErrorString(resultStr); return resultStr; } finally { @@ -584,9 +596,7 @@ export const scan = awaitInit(async (query: string): Promise => { resultPtr = callWasm(() => wasmModule._wasm_scan(queryPtr)); const resultStr = ptrToString(resultPtr); - if (resultStr.startsWith('syntax error') || resultStr.startsWith('deparse error') || resultStr.startsWith('ERROR')) { - throw new Error(resultStr); - } + throwIfErrorString(resultStr); return JSON.parse(resultStr); } finally { @@ -611,9 +621,7 @@ export function scanSync(query: string): ScanResult { resultPtr = callWasm(() => wasmModule._wasm_scan(queryPtr)); const resultStr = ptrToString(resultPtr); - if (resultStr.startsWith('syntax error') || resultStr.startsWith('deparse error') || resultStr.startsWith('ERROR')) { - throw new Error(resultStr); - } + throwIfErrorString(resultStr); return JSON.parse(resultStr); } finally { diff --git a/versions/18/src/wasm_wrapper.c b/versions/18/src/wasm_wrapper.c index 63ae5dab..f56e738f 100644 --- a/versions/18/src/wasm_wrapper.c +++ b/versions/18/src/wasm_wrapper.c @@ -6,8 +6,8 @@ */ #include "pg_query.h" -#include "protobuf/pg_query.pb-c.h" #include +#include #include #include #include @@ -237,7 +237,7 @@ void wasm_free_detailed_result(WasmDetailedResult* result) { } } -static const char* get_token_name(PgQuery__Token token_type) { +static const char* get_token_name(PgQueryToken token_type) { // Map some common token types to readable names // Note: This is a simplified mapping - full enum lookup would require more complexity switch(token_type) { @@ -262,7 +262,7 @@ static const char* get_token_name(PgQuery__Token token_type) { } } -static const char* get_keyword_name(PgQuery__KeywordKind keyword_kind) { +static const char* get_keyword_name(PgQueryKeywordKind keyword_kind) { switch(keyword_kind) { case 0: return "NO_KEYWORD"; case 1: return "UNRESERVED_KEYWORD"; @@ -273,7 +273,7 @@ static const char* get_keyword_name(PgQuery__KeywordKind keyword_kind) { } } -static char* build_scan_json(PgQuery__ScanResult *scan_result, const char* original_sql) { +static char* build_scan_json(const PgQueryScanTokensResult *scan_result, const char* original_sql) { if (!scan_result || !original_sql) { return safe_strdup("{\"version\":0,\"tokens\":[]}"); } @@ -282,29 +282,36 @@ static char* build_scan_json(PgQuery__ScanResult *scan_result, const char* origi // contributes at most ~170 bytes of fixed JSON plus up to 2 bytes per input // byte once escaped. size_t estimated_size = 1024; - for (size_t i = 0; i < scan_result->n_tokens; i++) { - PgQuery__ScanToken *token = scan_result->tokens[i]; + for (int i = 0; i < scan_result->n_tokens; i++) { + const PgQueryScanToken *token = &scan_result->tokens[i]; int token_length = token->end - token->start; if (token_length < 0) token_length = 0; - estimated_size += (size_t) token_length * 2 + 200; + size_t token_size = (size_t) token_length * 2 + 200; + if (estimated_size > SIZE_MAX - token_size) { + return safe_strdup("out of memory"); + } + estimated_size += token_size; } char* json = safe_malloc(estimated_size); if (!json) { - return safe_strdup("{\"version\":0,\"tokens\":[]}"); + return safe_strdup("out of memory"); } // Start building JSON - size_t pos = snprintf(json, estimated_size, "{\"version\":%d,\"tokens\":[", scan_result->version); + size_t pos = snprintf(json, estimated_size, "{\"version\":%d,\"tokens\":[", PG_VERSION_NUM); - for (size_t i = 0; i < scan_result->n_tokens; i++) { - PgQuery__ScanToken *token = scan_result->tokens[i]; + for (int i = 0; i < scan_result->n_tokens; i++) { + const PgQueryScanToken *token = &scan_result->tokens[i]; // Extract token text from original SQL int token_length = token->end - token->start; if (token_length < 0) token_length = 0; // Safety check char* token_text = safe_malloc(token_length + 1); - if (!token_text) continue; + if (!token_text) { + free(json); + return safe_strdup("out of memory"); + } if (token_length > 0) { strncpy(token_text, &original_sql[token->start], token_length); @@ -315,7 +322,8 @@ static char* build_scan_json(PgQuery__ScanResult *scan_result, const char* origi char* escaped_text = safe_malloc(token_length * 2 + 1); if (!escaped_text) { free(token_text); - continue; + free(json); + return safe_strdup("out of memory"); } int escaped_pos = 0; @@ -376,29 +384,17 @@ char* wasm_scan(const char* input) { return safe_strdup("Invalid input: query cannot be null or empty"); } - PgQueryScanResult result = pg_query_scan(input); + PgQueryScanTokensResult result = pg_query_scan_tokens(input); if (result.error) { char* error_msg = safe_strdup(result.error->message); - pg_query_free_scan_result(result); + pg_query_free_scan_tokens_result(result); return error_msg ? error_msg : safe_strdup("Memory allocation failed"); } - // Unpack protobuf data - PgQuery__ScanResult *scan_result = pg_query__scan_result__unpack( - NULL, result.pbuf.len, (void *) result.pbuf.data); - - if (!scan_result) { - pg_query_free_scan_result(result); - return safe_strdup("Failed to unpack scan result"); - } - - // Convert to JSON - char* json_result = build_scan_json(scan_result, input); + char* json_result = build_scan_json(&result, input); - // Clean up - pg_query__scan_result__free_unpacked(scan_result, NULL); - pg_query_free_scan_result(result); + pg_query_free_scan_tokens_result(result); return json_result ? json_result : safe_strdup("{\"version\":0,\"tokens\":[]}"); } diff --git a/versions/18/test/pg18.test.js b/versions/18/test/pg18.test.js index fb49bae0..ddcd446f 100644 --- a/versions/18/test/pg18.test.js +++ b/versions/18/test/pg18.test.js @@ -7,9 +7,9 @@ describe("PostgreSQL 18 syntax", () => { await loadModule(); }); - it("should report parser version 180004", async () => { + it("should report parser version 180006", async () => { const result = await parse("SELECT 1"); - assert.equal(result.version, 180004); + assert.equal(result.version, 180006); }); it("should parse RETURNING OLD/NEW aliases", async () => { @@ -61,7 +61,7 @@ describe("PostgreSQL 18 syntax", () => { const result = await scan( "UPDATE t SET a = 1 RETURNING OLD.a AS oa, NEW.a AS na" ); - assert.equal(result.version, 180004); + assert.equal(result.version, 180006); const texts = result.tokens.map((t) => t.text); assert.ok(texts.includes("OLD")); assert.ok(texts.includes("NEW")); diff --git a/versions/18/test/wasm-recovery.test.js b/versions/18/test/wasm-recovery.test.js index 6d16d379..48462e16 100644 --- a/versions/18/test/wasm-recovery.test.js +++ b/versions/18/test/wasm-recovery.test.js @@ -22,20 +22,14 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { assert.equal(parseSync('SELECT 1').stmts.length, 1); }); - // Without the 10-failure cap, about 45 overflows on one instance made the next one spin forever. - it('stops sync calls on the stale instance after 10 real overflows in one synchronous loop', async () => { + // libpg_query checks stack depth itself, so deeply nested SQL is a clean error + // and the instance is kept. The 10-failure cap on a stale instance is covered + // by the injected throws in 'Recovery from a throw in each entry point'. + it('returns a stack depth error for deeply nested SQL and keeps the instance', async () => { await loadModule(); - const errors = []; for (let i = 0; i < 60; i++) { - try { - parseSync(DEEP); - } catch (error) { - errors.push(error instanceof RangeError ? 'overflow' : error.message); - } + assert.throws(() => parseSync(DEEP), /stack depth limit exceeded/); } - assert.deepEqual(errors.slice(0, 10), Array(10).fill('overflow')); - for (const message of errors.slice(10)) assert.match(message, /Call `?loadModule\(\)`? first/); - await loadModule(); assert.equal(parseSync('SELECT 1').stmts.length, 1); }); @@ -109,10 +103,10 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { it('retries the load when loading a fresh instance fails', async () => { let loads = 0; - const isolated = loadIsolated((real, ...args) => - ++loads === 2 ? Promise.reject(new Error('simulated load failure')) : real(...args)); + const isolated = loadTrapping(() => ++loads === 2); await isolated.loadModule(); - await assert.rejects(isolated.parse(DEEP)); + isolated.trapNext(); + await assert.rejects(isolated.parse('SELECT 1'), RangeError); await new Promise((resolve) => setImmediate(resolve)); assert.equal((await isolated.parse('SELECT 1')).stmts.length, 1); assert.equal(loads, 3); @@ -120,10 +114,10 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { it('lets loadModule() reject on a failed reload and retry on the next call', async () => { let loads = 0; - const isolated = loadIsolated((real, ...args) => - ++loads === 2 ? Promise.reject(new Error('simulated load failure')) : real(...args)); + const isolated = loadTrapping(() => ++loads === 2); await isolated.loadModule(); - assert.throws(() => isolated.parseSync(DEEP)); + isolated.trapNext(); + assert.throws(() => isolated.parseSync('SELECT 1'), RangeError); await assert.rejects(isolated.loadModule(), /simulated load failure/); await isolated.loadModule(); assert.equal(isolated.parseSync('SELECT 1').stmts.length, 1); @@ -147,13 +141,14 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { it('retries a failed fresh load on the next failure, for callers that never await', async () => { let loads = 0; - const isolated = loadIsolated((real, ...args) => - ++loads === 2 ? Promise.reject(new Error('simulated load failure')) : real(...args)); + const isolated = loadTrapping(() => ++loads === 2); await isolated.loadModule(); - assert.throws(() => isolated.parseSync(DEEP)); + isolated.trapNext(); + assert.throws(() => isolated.parseSync('SELECT 1'), RangeError); await new Promise((resolve) => setImmediate(resolve)); assert.equal(loads, 2); - assert.throws(() => isolated.parseSync(DEEP)); + isolated.trapNext(); + assert.throws(() => isolated.parseSync('SELECT 1'), RangeError); assert.equal(loads, 3); await isolated.loadModule(); assert.equal(isolated.parseSync('SELECT 1').stmts.length, 1); @@ -335,6 +330,26 @@ describe('Recovery from a throw in each entry point', { timeout: 120000 }, () => } }); +// An isolated copy whose parse export throws once after trapNext(), standing in +// for a WASM trap now that libpg_query returns stack depth errors instead. +// failLoad() is called on each load; a true result rejects that load. +function loadTrapping(failLoad) { + let trap = false; + const isolated = loadIsolated(async (real, ...args) => { + if (failLoad()) throw new Error('simulated load failure'); + const module = await real(...args); + const parseRaw = module._wasm_parse_query_raw; + module._wasm_parse_query_raw = (...callArgs) => { + if (!trap) return parseRaw(...callArgs); + trap = false; + throw new RangeError('Maximum call stack size exceeded'); + }; + return module; + }); + isolated.trapNext = () => { trap = true; }; + return isolated; +} + // A copy of the wrapper whose WASM factory is wrapped, leaving the shared copy alone. function loadIsolated(wrapFactory) { const indexPath = require.resolve('../wasm/index.cjs'); From 00f09e556afe72175534ee39bdd64cf012e802a7 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Sun, 22 Nov 2026 19:32:18 +0000 Subject: [PATCH 2/2] chore(v18): pin libpg_query to 18-constructive (f75f801) after fork merge --- versions/18/Makefile | 4 ++-- versions/18/package.json | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/versions/18/Makefile b/versions/18/Makefile index 69ffe818..cbefe157 100644 --- a/versions/18/Makefile +++ b/versions/18/Makefile @@ -18,8 +18,8 @@ WASM_STACK_SIZE ?= 33554432 # libpg_query source, pinned to an exact commit so a release can be rebuilt # 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 := feat/pg18-combined-patches -LIBPG_QUERY_COMMIT := 0832f810aa38fb06358c761d0b1b246f337e9333 +LIBPG_QUERY_TAG := 18-constructive +LIBPG_QUERY_COMMIT := f75f8010a8a75fe4645db550c5f8f435dbc938a3 CACHE_DIR := .cache diff --git a/versions/18/package.json b/versions/18/package.json index d976c98b..178c8b84 100644 --- a/versions/18/package.json +++ b/versions/18/package.json @@ -14,8 +14,8 @@ "pgVersion": "18", "distTag": "pg18", "libpgQueryRepo": "https://github.com/constructive-io/libpg_query.git", - "libpgQueryTag": "feat/pg18-combined-patches", - "libpgQueryCommit": "0832f810aa38fb06358c761d0b1b246f337e9333", + "libpgQueryTag": "18-constructive", + "libpgQueryCommit": "f75f8010a8a75fe4645db550c5f8f435dbc938a3", "fullApi": true }, "files": [