From 19ebadaefa48b333101543a11620ba5b19566110 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Tue, 24 Nov 2026 18:09:09 +0000 Subject: [PATCH 1/6] fix(v18): throw SqlError for fingerprint, normalize, and scan --- templates/full/index.ts | 185 ++++++++------------------- templates/full/libpg-query.d.ts | 2 + templates/full/wasm_wrapper.c | 140 ++++++++++---------- versions/18/README_ERROR_HANDLING.md | 2 +- versions/18/src/index.ts | 185 ++++++++------------------- versions/18/src/libpg-query.d.ts | 2 + versions/18/src/wasm_wrapper.c | 140 ++++++++++---------- versions/18/test/pg18.test.js | 49 ++++++- 8 files changed, 299 insertions(+), 406 deletions(-) diff --git a/templates/full/index.ts b/templates/full/index.ts index 1caa6833..1fa3582a 100644 --- a/templates/full/index.ts +++ b/templates/full/index.ts @@ -120,6 +120,7 @@ interface WasmModule { _malloc: (size: number) => number; _free: (ptr: number) => void; _wasm_free_string: (ptr: number) => void; + _wasm_free_detailed_result: (ptr: number) => void; _wasm_parse_query: (queryPtr: number) => number; _wasm_parse_query_raw: (queryPtr: number) => number; _wasm_free_parse_result: (ptr: number) => void; @@ -220,13 +221,6 @@ function outOfMemoryError(): Error { 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."); } @@ -300,6 +294,52 @@ function ptrToString(ptr: number): string { return wasmModule.UTF8ToString(ptr); } +type DetailedOperation = '_wasm_fingerprint' | '_wasm_normalize_query' | '_wasm_scan'; + +function callDetailed(query: string, operation: DetailedOperation): string { + if (!wasmModule) { + throw new Error('WASM module not initialized. Call loadModule() first.'); + } + const queryPtr = stringToPtr(query); + const failuresBefore = failures; + let resultPtr = 0; + + try { + resultPtr = callWasm(() => wasmModule[operation](queryPtr)); + if (!resultPtr) throw outOfMemoryError(); + + // WasmDetailedResult uses 32-bit fields and pointers. + if (wasmModule.getValue(resultPtr, 'i32')) { + const readString = (offset: number) => { + const ptr = wasmModule.getValue(resultPtr + offset, 'i32'); + return ptr ? wasmModule.UTF8ToString(ptr) : undefined; + }; + const message = readString(4) ?? 'Unknown error'; + if (message === 'out of memory') throw outOfMemoryError(); + + const lineno = wasmModule.getValue(resultPtr + 16, 'i32'); + const cursorpos = wasmModule.getValue(resultPtr + 20, 'i32'); + const context = readString(24); + throw new SqlError(message, { + message, + cursorPosition: cursorpos > 0 ? cursorpos - 1 : 0, + fileName: readString(12), + functionName: readString(8), + lineNumber: lineno > 0 ? lineno : undefined, + ...(context !== undefined ? { context } : {}) + }); + } + return wasmModule.UTF8ToString(wasmModule.getValue(resultPtr + 28, 'i32')); + } finally { + if (failures === failuresBefore) { + wasmModule._free(queryPtr); + if (resultPtr) { + wasmModule._wasm_free_detailed_result(resultPtr); + } + } + } +} + export const parse = awaitInit(async (query: string): Promise => { // Input validation if (query === null || query === undefined) { @@ -390,47 +430,11 @@ export const parsePlPgSQL = awaitInit(async (query: string): Promise => { - const queryPtr = stringToPtr(query); - const failuresBefore = failures; - let resultPtr = 0; - - try { - resultPtr = callWasm(() => wasmModule._wasm_fingerprint(queryPtr)); - const resultStr = ptrToString(resultPtr); - - throwIfErrorString(resultStr); - - return resultStr; - } finally { - if (failures === failuresBefore) { - wasmModule._free(queryPtr); - if (resultPtr) { - wasmModule._wasm_free_string(resultPtr); - } - } - } + return callDetailed(query, '_wasm_fingerprint'); }); export const normalize = awaitInit(async (query: string): Promise => { - const queryPtr = stringToPtr(query); - const failuresBefore = failures; - let resultPtr = 0; - - try { - resultPtr = callWasm(() => wasmModule._wasm_normalize_query(queryPtr)); - const resultStr = ptrToString(resultPtr); - - throwIfErrorString(resultStr); - - return resultStr; - } finally { - if (failures === failuresBefore) { - wasmModule._free(queryPtr); - if (resultPtr) { - wasmModule._wasm_free_string(resultPtr); - } - } - } + return callDetailed(query, '_wasm_normalize_query'); }); // Sync versions @@ -531,98 +535,17 @@ export function parsePlPgSQLSync(query: string): ParseResult { } export function fingerprintSync(query: string): string { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } - const queryPtr = stringToPtr(query); - const failuresBefore = failures; - let resultPtr = 0; - - try { - resultPtr = callWasm(() => wasmModule._wasm_fingerprint(queryPtr)); - const resultStr = ptrToString(resultPtr); - - throwIfErrorString(resultStr); - - return resultStr; - } finally { - if (failures === failuresBefore) { - wasmModule._free(queryPtr); - if (resultPtr) { - wasmModule._wasm_free_string(resultPtr); - } - } - } + return callDetailed(query, '_wasm_fingerprint'); } export function normalizeSync(query: string): string { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } - const queryPtr = stringToPtr(query); - const failuresBefore = failures; - let resultPtr = 0; - - try { - resultPtr = callWasm(() => wasmModule._wasm_normalize_query(queryPtr)); - const resultStr = ptrToString(resultPtr); - - throwIfErrorString(resultStr); - - return resultStr; - } finally { - if (failures === failuresBefore) { - wasmModule._free(queryPtr); - if (resultPtr) { - wasmModule._wasm_free_string(resultPtr); - } - } - } + return callDetailed(query, '_wasm_normalize_query'); } export const scan = awaitInit(async (query: string): Promise => { - const queryPtr = stringToPtr(query); - const failuresBefore = failures; - let resultPtr = 0; - - try { - resultPtr = callWasm(() => wasmModule._wasm_scan(queryPtr)); - const resultStr = ptrToString(resultPtr); - - throwIfErrorString(resultStr); - - return JSON.parse(resultStr); - } finally { - if (failures === failuresBefore) { - wasmModule._free(queryPtr); - if (resultPtr) { - wasmModule._wasm_free_string(resultPtr); - } - } - } + return JSON.parse(callDetailed(query, '_wasm_scan')); }); export function scanSync(query: string): ScanResult { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } - const queryPtr = stringToPtr(query); - const failuresBefore = failures; - let resultPtr = 0; - - try { - resultPtr = callWasm(() => wasmModule._wasm_scan(queryPtr)); - const resultStr = ptrToString(resultPtr); - - throwIfErrorString(resultStr); - - return JSON.parse(resultStr); - } finally { - if (failures === failuresBefore) { - wasmModule._free(queryPtr); - if (resultPtr) { - wasmModule._wasm_free_string(resultPtr); - } - } - } -} \ No newline at end of file + return JSON.parse(callDetailed(query, '_wasm_scan')); +} \ No newline at end of file diff --git a/templates/full/libpg-query.d.ts b/templates/full/libpg-query.d.ts index 731e1a99..7fcbfb0d 100644 --- a/templates/full/libpg-query.d.ts +++ b/templates/full/libpg-query.d.ts @@ -3,10 +3,12 @@ declare module './libpg-query.js' { _malloc: (size: number) => number; _free: (ptr: number) => void; _wasm_free_string: (ptr: number) => void; + _wasm_free_detailed_result: (ptr: number) => void; _wasm_parse_query: (queryPtr: number) => number; _wasm_parse_plpgsql: (queryPtr: number) => number; _wasm_fingerprint: (queryPtr: number) => number; _wasm_normalize_query: (queryPtr: number) => number; + _wasm_scan: (queryPtr: number) => number; lengthBytesUTF8: (str: string) => number; stringToUTF8: (str: string, ptr: number, len: number) => void; UTF8ToString: (ptr: number) => string; diff --git a/templates/full/wasm_wrapper.c b/templates/full/wasm_wrapper.c index 4d726ef8..ac6e6b41 100644 --- a/templates/full/wasm_wrapper.c +++ b/templates/full/wasm_wrapper.c @@ -104,53 +104,6 @@ char* wasm_parse_plpgsql(const char* input) { return wrapped_result; } -EMSCRIPTEN_KEEPALIVE -char* wasm_fingerprint(const char* input) { - if (!validate_input(input)) { - return safe_strdup("Invalid input: query cannot be null or empty"); - } - - PgQueryFingerprintResult result = pg_query_fingerprint(input); - - if (result.error) { - char* error_msg = safe_strdup(result.error->message); - pg_query_free_fingerprint_result(result); - return error_msg ? error_msg : safe_strdup("Memory allocation failed"); - } - - char* fingerprint_str = safe_strdup(result.fingerprint_str); - pg_query_free_fingerprint_result(result); - return fingerprint_str; -} - -EMSCRIPTEN_KEEPALIVE -char* wasm_normalize_query(const char* input) { - if (!validate_input(input)) { - return safe_strdup("Invalid input: query cannot be null or empty"); - } - - PgQueryNormalizeResult result = pg_query_normalize(input); - - if (result.error) { - char* error_msg = safe_strdup(result.error->message); - pg_query_free_normalize_result(result); - return error_msg ? error_msg : safe_strdup("Memory allocation failed"); - } - - char* normalized = safe_strdup(result.normalized_query); - pg_query_free_normalize_result(result); - - if (!normalized) { - return safe_strdup("Memory allocation failed"); - } - - return normalized; -} - - - - - typedef struct { int has_error; char* message; @@ -230,6 +183,65 @@ void wasm_free_detailed_result(WasmDetailedResult* result) { } } +// Takes ownership of data and copies any error before libpg_query frees it. +static WasmDetailedResult* make_detailed_result(char* data, const PgQueryError* error) { + if (!data && !error) return NULL; + + WasmDetailedResult* result = calloc(1, sizeof(WasmDetailedResult)); + if (!result) { + free(data); + return NULL; + } + + result->data = data; + if (error) { + result->has_error = 1; + result->message = safe_strdup(error->message); + result->funcname = safe_strdup(error->funcname); + result->filename = safe_strdup(error->filename); + result->lineno = error->lineno; + result->cursorpos = error->cursorpos; + result->context = safe_strdup(error->context); + if ((error->message && !result->message) || + (error->funcname && !result->funcname) || + (error->filename && !result->filename) || + (error->context && !result->context)) { + wasm_free_detailed_result(result); + return NULL; + } + } else { + result->data_len = strlen(data); + } + return result; +} + +static WasmDetailedResult* invalid_input_result(void) { + const PgQueryError error = { .message = "Invalid input: query cannot be null or empty" }; + return make_detailed_result(NULL, &error); +} + +EMSCRIPTEN_KEEPALIVE +WasmDetailedResult* wasm_fingerprint(const char* input) { + if (!validate_input(input)) return invalid_input_result(); + + PgQueryFingerprintResult result = pg_query_fingerprint(input); + WasmDetailedResult* detailed = make_detailed_result( + result.error ? NULL : safe_strdup(result.fingerprint_str), result.error); + pg_query_free_fingerprint_result(result); + return detailed; +} + +EMSCRIPTEN_KEEPALIVE +WasmDetailedResult* wasm_normalize_query(const char* input) { + if (!validate_input(input)) return invalid_input_result(); + + PgQueryNormalizeResult result = pg_query_normalize(input); + WasmDetailedResult* detailed = make_detailed_result( + result.error ? NULL : safe_strdup(result.normalized_query), result.error); + pg_query_free_normalize_result(result); + return detailed; +} + 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 @@ -267,10 +279,6 @@ static const char* get_keyword_name(PgQueryKeywordKind keyword_kind) { } static char* build_scan_json(const PgQueryScanTokensResult *scan_result, const char* original_sql) { - if (!scan_result || !original_sql) { - return safe_strdup("{\"version\":0,\"tokens\":[]}"); - } - // Size the buffer from token text length, not token count: each token // contributes at most ~170 bytes of fixed JSON plus up to 2 bytes per input // byte once escaped. @@ -281,13 +289,13 @@ static char* build_scan_json(const PgQueryScanTokensResult *scan_result, const c if (token_length < 0) token_length = 0; size_t token_size = (size_t) token_length * 2 + 200; if (estimated_size > SIZE_MAX - token_size) { - return safe_strdup("out of memory"); + return NULL; } estimated_size += token_size; } char* json = safe_malloc(estimated_size); if (!json) { - return safe_strdup("out of memory"); + return NULL; } // Start building JSON @@ -303,7 +311,7 @@ static char* build_scan_json(const PgQueryScanTokensResult *scan_result, const c char* token_text = safe_malloc(token_length + 1); if (!token_text) { free(json); - return safe_strdup("out of memory"); + return NULL; } if (token_length > 0) { @@ -316,7 +324,7 @@ static char* build_scan_json(const PgQueryScanTokensResult *scan_result, const c if (!escaped_text) { free(token_text); free(json); - return safe_strdup("out of memory"); + return NULL; } int escaped_pos = 0; @@ -372,24 +380,14 @@ static char* build_scan_json(const PgQueryScanTokensResult *scan_result, const c } EMSCRIPTEN_KEEPALIVE -char* wasm_scan(const char* input) { - if (!validate_input(input)) { - return safe_strdup("Invalid input: query cannot be null or empty"); - } - +WasmDetailedResult* wasm_scan(const char* input) { + if (!validate_input(input)) return invalid_input_result(); + PgQueryScanTokensResult result = pg_query_scan_tokens(input); - - if (result.error) { - char* error_msg = safe_strdup(result.error->message); - pg_query_free_scan_tokens_result(result); - return error_msg ? error_msg : safe_strdup("Memory allocation failed"); - } - - char* json_result = build_scan_json(&result, input); - + WasmDetailedResult* detailed = make_detailed_result( + result.error ? NULL : build_scan_json(&result, input), result.error); pg_query_free_scan_tokens_result(result); - - return json_result ? json_result : safe_strdup("{\"version\":0,\"tokens\":[]}"); + return detailed; } EMSCRIPTEN_KEEPALIVE diff --git a/versions/18/README_ERROR_HANDLING.md b/versions/18/README_ERROR_HANDLING.md index c9f23c65..522f6397 100644 --- a/versions/18/README_ERROR_HANDLING.md +++ b/versions/18/README_ERROR_HANDLING.md @@ -6,7 +6,7 @@ Version 18 includes enhanced error handling that provides detailed information a ## Error Details -When a parsing error occurs, the error object now includes a `sqlDetails` property with the following information: +PostgreSQL errors from `parse`, `fingerprint`, `normalize`, and `scan` (including their sync variants) throw a `SqlError` with a `sqlDetails` property: ```typescript interface SqlErrorDetails { diff --git a/versions/18/src/index.ts b/versions/18/src/index.ts index 5082f7f9..bcb2896b 100644 --- a/versions/18/src/index.ts +++ b/versions/18/src/index.ts @@ -127,6 +127,7 @@ interface WasmModule { _malloc: (size: number) => number; _free: (ptr: number) => void; _wasm_free_string: (ptr: number) => void; + _wasm_free_detailed_result: (ptr: number) => void; _wasm_parse_query: (queryPtr: number) => number; _wasm_parse_query_raw: (queryPtr: number) => number; _wasm_free_parse_result: (ptr: number) => void; @@ -227,13 +228,6 @@ function outOfMemoryError(): Error { 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."); } @@ -307,6 +301,52 @@ function ptrToString(ptr: number): string { return wasmModule.UTF8ToString(ptr); } +type DetailedOperation = '_wasm_fingerprint' | '_wasm_normalize_query' | '_wasm_scan'; + +function callDetailed(query: string, operation: DetailedOperation): string { + if (!wasmModule) { + throw new Error('WASM module not initialized. Call loadModule() first.'); + } + const queryPtr = stringToPtr(query); + const failuresBefore = failures; + let resultPtr = 0; + + try { + resultPtr = callWasm(() => wasmModule[operation](queryPtr)); + if (!resultPtr) throw outOfMemoryError(); + + // WasmDetailedResult uses 32-bit fields and pointers. + if (wasmModule.getValue(resultPtr, 'i32')) { + const readString = (offset: number) => { + const ptr = wasmModule.getValue(resultPtr + offset, 'i32'); + return ptr ? wasmModule.UTF8ToString(ptr) : undefined; + }; + const message = readString(4) ?? 'Unknown error'; + if (message === 'out of memory') throw outOfMemoryError(); + + const lineno = wasmModule.getValue(resultPtr + 16, 'i32'); + const cursorpos = wasmModule.getValue(resultPtr + 20, 'i32'); + const context = readString(24); + throw new SqlError(message, { + message, + cursorPosition: cursorpos > 0 ? cursorpos - 1 : 0, + fileName: readString(12), + functionName: readString(8), + lineNumber: lineno > 0 ? lineno : undefined, + ...(context !== undefined ? { context } : {}) + }); + } + return wasmModule.UTF8ToString(wasmModule.getValue(resultPtr + 28, 'i32')); + } finally { + if (failures === failuresBefore) { + wasmModule._free(queryPtr); + if (resultPtr) { + wasmModule._wasm_free_detailed_result(resultPtr); + } + } + } +} + export const parse = awaitInit(async (query: string): Promise => { // Input validation if (query === null || query === undefined) { @@ -397,47 +437,11 @@ export const parsePlPgSQL = awaitInit(async (query: string): Promise => { - const queryPtr = stringToPtr(query); - const failuresBefore = failures; - let resultPtr = 0; - - try { - resultPtr = callWasm(() => wasmModule._wasm_fingerprint(queryPtr)); - const resultStr = ptrToString(resultPtr); - - throwIfErrorString(resultStr); - - return resultStr; - } finally { - if (failures === failuresBefore) { - wasmModule._free(queryPtr); - if (resultPtr) { - wasmModule._wasm_free_string(resultPtr); - } - } - } + return callDetailed(query, '_wasm_fingerprint'); }); export const normalize = awaitInit(async (query: string): Promise => { - const queryPtr = stringToPtr(query); - const failuresBefore = failures; - let resultPtr = 0; - - try { - resultPtr = callWasm(() => wasmModule._wasm_normalize_query(queryPtr)); - const resultStr = ptrToString(resultPtr); - - throwIfErrorString(resultStr); - - return resultStr; - } finally { - if (failures === failuresBefore) { - wasmModule._free(queryPtr); - if (resultPtr) { - wasmModule._wasm_free_string(resultPtr); - } - } - } + return callDetailed(query, '_wasm_normalize_query'); }); // Sync versions @@ -538,98 +542,17 @@ export function parsePlPgSQLSync(query: string): ParseResult { } export function fingerprintSync(query: string): string { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } - const queryPtr = stringToPtr(query); - const failuresBefore = failures; - let resultPtr = 0; - - try { - resultPtr = callWasm(() => wasmModule._wasm_fingerprint(queryPtr)); - const resultStr = ptrToString(resultPtr); - - throwIfErrorString(resultStr); - - return resultStr; - } finally { - if (failures === failuresBefore) { - wasmModule._free(queryPtr); - if (resultPtr) { - wasmModule._wasm_free_string(resultPtr); - } - } - } + return callDetailed(query, '_wasm_fingerprint'); } export function normalizeSync(query: string): string { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } - const queryPtr = stringToPtr(query); - const failuresBefore = failures; - let resultPtr = 0; - - try { - resultPtr = callWasm(() => wasmModule._wasm_normalize_query(queryPtr)); - const resultStr = ptrToString(resultPtr); - - throwIfErrorString(resultStr); - - return resultStr; - } finally { - if (failures === failuresBefore) { - wasmModule._free(queryPtr); - if (resultPtr) { - wasmModule._wasm_free_string(resultPtr); - } - } - } + return callDetailed(query, '_wasm_normalize_query'); } export const scan = awaitInit(async (query: string): Promise => { - const queryPtr = stringToPtr(query); - const failuresBefore = failures; - let resultPtr = 0; - - try { - resultPtr = callWasm(() => wasmModule._wasm_scan(queryPtr)); - const resultStr = ptrToString(resultPtr); - - throwIfErrorString(resultStr); - - return JSON.parse(resultStr); - } finally { - if (failures === failuresBefore) { - wasmModule._free(queryPtr); - if (resultPtr) { - wasmModule._wasm_free_string(resultPtr); - } - } - } + return JSON.parse(callDetailed(query, '_wasm_scan')); }); export function scanSync(query: string): ScanResult { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } - const queryPtr = stringToPtr(query); - const failuresBefore = failures; - let resultPtr = 0; - - try { - resultPtr = callWasm(() => wasmModule._wasm_scan(queryPtr)); - const resultStr = ptrToString(resultPtr); - - throwIfErrorString(resultStr); - - return JSON.parse(resultStr); - } finally { - if (failures === failuresBefore) { - wasmModule._free(queryPtr); - if (resultPtr) { - wasmModule._wasm_free_string(resultPtr); - } - } - } -} \ No newline at end of file + return JSON.parse(callDetailed(query, '_wasm_scan')); +} \ No newline at end of file diff --git a/versions/18/src/libpg-query.d.ts b/versions/18/src/libpg-query.d.ts index 152d8414..a556fa66 100644 --- a/versions/18/src/libpg-query.d.ts +++ b/versions/18/src/libpg-query.d.ts @@ -10,10 +10,12 @@ declare module './libpg-query.js' { _malloc: (size: number) => number; _free: (ptr: number) => void; _wasm_free_string: (ptr: number) => void; + _wasm_free_detailed_result: (ptr: number) => void; _wasm_parse_query: (queryPtr: number) => number; _wasm_parse_plpgsql: (queryPtr: number) => number; _wasm_fingerprint: (queryPtr: number) => number; _wasm_normalize_query: (queryPtr: number) => number; + _wasm_scan: (queryPtr: number) => number; lengthBytesUTF8: (str: string) => number; stringToUTF8: (str: string, ptr: number, len: number) => void; UTF8ToString: (ptr: number) => string; diff --git a/versions/18/src/wasm_wrapper.c b/versions/18/src/wasm_wrapper.c index f56e738f..26802324 100644 --- a/versions/18/src/wasm_wrapper.c +++ b/versions/18/src/wasm_wrapper.c @@ -111,53 +111,6 @@ char* wasm_parse_plpgsql(const char* input) { return wrapped_result; } -EMSCRIPTEN_KEEPALIVE -char* wasm_fingerprint(const char* input) { - if (!validate_input(input)) { - return safe_strdup("Invalid input: query cannot be null or empty"); - } - - PgQueryFingerprintResult result = pg_query_fingerprint(input); - - if (result.error) { - char* error_msg = safe_strdup(result.error->message); - pg_query_free_fingerprint_result(result); - return error_msg ? error_msg : safe_strdup("Memory allocation failed"); - } - - char* fingerprint_str = safe_strdup(result.fingerprint_str); - pg_query_free_fingerprint_result(result); - return fingerprint_str; -} - -EMSCRIPTEN_KEEPALIVE -char* wasm_normalize_query(const char* input) { - if (!validate_input(input)) { - return safe_strdup("Invalid input: query cannot be null or empty"); - } - - PgQueryNormalizeResult result = pg_query_normalize(input); - - if (result.error) { - char* error_msg = safe_strdup(result.error->message); - pg_query_free_normalize_result(result); - return error_msg ? error_msg : safe_strdup("Memory allocation failed"); - } - - char* normalized = safe_strdup(result.normalized_query); - pg_query_free_normalize_result(result); - - if (!normalized) { - return safe_strdup("Memory allocation failed"); - } - - return normalized; -} - - - - - typedef struct { int has_error; char* message; @@ -237,6 +190,65 @@ void wasm_free_detailed_result(WasmDetailedResult* result) { } } +// Takes ownership of data and copies any error before libpg_query frees it. +static WasmDetailedResult* make_detailed_result(char* data, const PgQueryError* error) { + if (!data && !error) return NULL; + + WasmDetailedResult* result = calloc(1, sizeof(WasmDetailedResult)); + if (!result) { + free(data); + return NULL; + } + + result->data = data; + if (error) { + result->has_error = 1; + result->message = safe_strdup(error->message); + result->funcname = safe_strdup(error->funcname); + result->filename = safe_strdup(error->filename); + result->lineno = error->lineno; + result->cursorpos = error->cursorpos; + result->context = safe_strdup(error->context); + if ((error->message && !result->message) || + (error->funcname && !result->funcname) || + (error->filename && !result->filename) || + (error->context && !result->context)) { + wasm_free_detailed_result(result); + return NULL; + } + } else { + result->data_len = strlen(data); + } + return result; +} + +static WasmDetailedResult* invalid_input_result(void) { + const PgQueryError error = { .message = "Invalid input: query cannot be null or empty" }; + return make_detailed_result(NULL, &error); +} + +EMSCRIPTEN_KEEPALIVE +WasmDetailedResult* wasm_fingerprint(const char* input) { + if (!validate_input(input)) return invalid_input_result(); + + PgQueryFingerprintResult result = pg_query_fingerprint(input); + WasmDetailedResult* detailed = make_detailed_result( + result.error ? NULL : safe_strdup(result.fingerprint_str), result.error); + pg_query_free_fingerprint_result(result); + return detailed; +} + +EMSCRIPTEN_KEEPALIVE +WasmDetailedResult* wasm_normalize_query(const char* input) { + if (!validate_input(input)) return invalid_input_result(); + + PgQueryNormalizeResult result = pg_query_normalize(input); + WasmDetailedResult* detailed = make_detailed_result( + result.error ? NULL : safe_strdup(result.normalized_query), result.error); + pg_query_free_normalize_result(result); + return detailed; +} + 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 @@ -274,10 +286,6 @@ static const char* get_keyword_name(PgQueryKeywordKind keyword_kind) { } static char* build_scan_json(const PgQueryScanTokensResult *scan_result, const char* original_sql) { - if (!scan_result || !original_sql) { - return safe_strdup("{\"version\":0,\"tokens\":[]}"); - } - // Size the buffer from token text length, not token count: each token // contributes at most ~170 bytes of fixed JSON plus up to 2 bytes per input // byte once escaped. @@ -288,13 +296,13 @@ static char* build_scan_json(const PgQueryScanTokensResult *scan_result, const c if (token_length < 0) token_length = 0; size_t token_size = (size_t) token_length * 2 + 200; if (estimated_size > SIZE_MAX - token_size) { - return safe_strdup("out of memory"); + return NULL; } estimated_size += token_size; } char* json = safe_malloc(estimated_size); if (!json) { - return safe_strdup("out of memory"); + return NULL; } // Start building JSON @@ -310,7 +318,7 @@ static char* build_scan_json(const PgQueryScanTokensResult *scan_result, const c char* token_text = safe_malloc(token_length + 1); if (!token_text) { free(json); - return safe_strdup("out of memory"); + return NULL; } if (token_length > 0) { @@ -323,7 +331,7 @@ static char* build_scan_json(const PgQueryScanTokensResult *scan_result, const c if (!escaped_text) { free(token_text); free(json); - return safe_strdup("out of memory"); + return NULL; } int escaped_pos = 0; @@ -379,24 +387,14 @@ static char* build_scan_json(const PgQueryScanTokensResult *scan_result, const c } EMSCRIPTEN_KEEPALIVE -char* wasm_scan(const char* input) { - if (!validate_input(input)) { - return safe_strdup("Invalid input: query cannot be null or empty"); - } - +WasmDetailedResult* wasm_scan(const char* input) { + if (!validate_input(input)) return invalid_input_result(); + PgQueryScanTokensResult result = pg_query_scan_tokens(input); - - if (result.error) { - char* error_msg = safe_strdup(result.error->message); - pg_query_free_scan_tokens_result(result); - return error_msg ? error_msg : safe_strdup("Memory allocation failed"); - } - - char* json_result = build_scan_json(&result, input); - + WasmDetailedResult* detailed = make_detailed_result( + result.error ? NULL : build_scan_json(&result, input), result.error); pg_query_free_scan_tokens_result(result); - - return json_result ? json_result : safe_strdup("{\"version\":0,\"tokens\":[]}"); + return detailed; } EMSCRIPTEN_KEEPALIVE diff --git a/versions/18/test/pg18.test.js b/versions/18/test/pg18.test.js index ddcd446f..c8dd1dae 100644 --- a/versions/18/test/pg18.test.js +++ b/versions/18/test/pg18.test.js @@ -1,6 +1,9 @@ const { describe, it, before } = require("node:test"); const assert = require("node:assert"); -const { parse, parseSync, parsePlPgSQL, scan, loadModule } = require("../"); +const { + parse, parseSync, parsePlPgSQL, scan, scanSync, loadModule, SqlError, + fingerprint, fingerprintSync, normalize, normalizeSync +} = require("../"); describe("PostgreSQL 18 syntax", () => { before(async () => { @@ -67,3 +70,47 @@ describe("PostgreSQL 18 syntax", () => { assert.ok(texts.includes("NEW")); }); }); + +describe("PostgreSQL 18 structured SQL errors", () => { + before(async () => { + await loadModule(); + }); + + const lexerError = { + sql: "SELECT 'abc", + message: /unterminated quoted string/, + fileName: /scan\.l$/, + cursorPosition: 7 + }; + const grammarError = { + sql: "SELECT percentile_cont(p ORDER BY p) WITHIN GROUP (ORDER BY x) FROM t", + message: /cannot use multiple ORDER BY clauses with WITHIN GROUP/, + fileName: /gram\.y$/ + }; + + for (const [run, runSync, cases] of [ + [fingerprint, fingerprintSync, [lexerError, grammarError]], + [normalize, normalizeSync, [lexerError, grammarError]], + [scan, scanSync, [lexerError]] + ]) { + it(`${runSync.name} throws and its async counterpart rejects with SqlError`, async () => { + for (const { sql, message, fileName, cursorPosition } of cases) { + const checkError = (error) => { + assert.ok(error instanceof SqlError); + assert.match(error.message, message); + const details = error.sqlDetails; + assert.equal(details.message, error.message); + assert.match(details.fileName, fileName); + assert.ok(details.functionName); + assert.ok(details.lineNumber > 0); + if (cursorPosition !== undefined) { + assert.equal(details.cursorPosition, cursorPosition); + } + return true; + }; + assert.throws(() => runSync(sql), checkError); + await assert.rejects(run(sql), checkError); + } + }); + } +}); From 599bcd2c13ec798f0b470a8ced1418bb66ab4652 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Tue, 24 Nov 2026 18:10:59 +0000 Subject: [PATCH 2/6] fix(wasm): recover synchronous PG 18 parser calls --- scripts/copy-templates.js | 5 +- templates/full/index.ts | 117 ++++++++++++------------- templates/full/pre.js | 23 +++++ versions/18/src/index.ts | 117 ++++++++++++------------- versions/18/src/pre.js | 24 +++++ versions/18/test/load-module.test.js | 12 ++- versions/18/test/wasm-recovery.test.js | 90 +++++++++---------- 7 files changed, 206 insertions(+), 182 deletions(-) create mode 100644 templates/full/pre.js diff --git a/scripts/copy-templates.js b/scripts/copy-templates.js index 58930386..26aba149 100755 --- a/scripts/copy-templates.js +++ b/scripts/copy-templates.js @@ -66,7 +66,7 @@ const TEMPLATE_FILES = [ { src: 'wasm_wrapper.c', dest: 'src/wasm_wrapper.c', header: HEADER, hasFullVariant: true }, { src: 'libpg-query.d.ts', dest: 'src/libpg-query.d.ts', header: HEADER, hasFullVariant: true }, { src: 'index.ts', dest: 'src/index.ts', header: HEADER, hasFullVariant: true }, - { src: 'pre.js', dest: 'src/pre.js', header: HEADER, hasFullVariant: false } + { src: 'pre.js', dest: 'src/pre.js', header: HEADER, appendFullVariant: true } ]; const SLIM_EXPORTED_FUNCTIONS = "['_malloc','_free','_wasm_parse_query_raw','_wasm_free_parse_result']"; @@ -96,6 +96,9 @@ function copyTemplates() { // Read template content let content = fs.readFileSync(srcPath, 'utf8'); + if (config.fullApi && file.appendFullVariant) { + content += '\n' + fs.readFileSync(path.join(templatesDir, 'full', file.src), 'utf8'); + } // Add header if specified if (file.header) { diff --git a/templates/full/index.ts b/templates/full/index.ts index 1caa6833..5edd4d17 100644 --- a/templates/full/index.ts +++ b/templates/full/index.ts @@ -117,6 +117,7 @@ export function formatSqlError( import PgQueryModule from './libpg-query.js'; interface WasmModule { + compiledWasm: WasmCompiledModule; _malloc: (size: number) => number; _free: (ptr: number) => void; _wasm_free_string: (ptr: number) => void; @@ -135,49 +136,34 @@ interface WasmModule { } let wasmModule: WasmModule; - -// After a WASM call throws, the instance is stale: async calls wait for its -// replacement, while sync calls, which cannot wait, keep using it until the -// replacement is ready. One replacement loads at a time; the next call retries -// a failed load. -let stale = false; +let compiledWasm: WasmCompiledModule | undefined; let loading: Promise | undefined; -// Counts WASM calls that threw, so cleanup skips an instance that threw mid-call. +// Invalidation skips cleanup through pointers that belong to a failed instance. let failures = 0; -// Sync calls stop using a stale instance after this many failures on it: past -// about 45, a stack overflow can make the next one spin forever. -const MAX_STALE_FAILURES = 10; -let staleFailures = 0; -// Set by loadModule({ wasm }); instances are then created from it instead of the file. -let provided: WasmCompiledModule | undefined; - -function createModule(): Promise { - const module = provided; - if (!module) return PgQueryModule(); - return new Promise((resolve, reject) => { - PgQueryModule({ - instantiateWasm(imports: any, receive: (instance: any) => void) { - WebAssembly.instantiate(module, imports).then(receive, reject); - return {}; - }, - }).then(resolve, reject); - }); +// Dropped instances can remain live until the current synchronous run yields. +const LARGE_HEAP_BYTES = 512 * 1024 * 1024; +let largeFailures = 0; +let memoryLimitError: Error | undefined; + +function createSync(module: WasmCompiledModule): WasmModule { + const options: Partial & { readySync?: boolean; initError?: unknown } = { + compiledWasm: module, + }; + PgQueryModule(options).catch(() => {}); + if (!options.readySync) { + throw new Error('Could not start a fresh WASM instance', { cause: options.initError }); + } + return options as WasmModule; } function instantiate(): Promise { if (loading) return loading; - const promise = createModule().then( - (module: WasmModule) => { - wasmModule = module; - stale = false; - staleFailures = 0; - loading = undefined; - }, - (error: unknown) => { - loading = undefined; - throw error; + const promise = Promise.resolve().then(async () => { + if (!wasmModule) { + wasmModule = compiledWasm ? createSync(compiledWasm) : await PgQueryModule(); + compiledWasm = wasmModule.compiledWasm; } - ); + }).finally(() => { loading = undefined; }); loading = promise; // Rejects only for the callers awaiting it. promise.catch(() => {}); @@ -186,6 +172,24 @@ function instantiate(): Promise { instantiate(); +function invalidateModule(error: unknown): void { + if (wasmModule.HEAPU8.length > LARGE_HEAP_BYTES) { + if (++largeFailures === 1) { + queueMicrotask(() => { + largeFailures = 0; + memoryLimitError = undefined; + }); + } else { + memoryLimitError = new Error( + 'WASM memory limit hit repeatedly in one synchronous run; yield (await) before retrying', + { cause: error } + ); + } + } + failures++; + wasmModule = undefined; +} + // An exception out of a WASM call (V8 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. @@ -195,11 +199,8 @@ function callWasm(fn: () => number): number { try { return fn(); } catch (error) { - failures++; - stale = true; - if (++staleFailures >= MAX_STALE_FAILURES) wasmModule = undefined; - instantiate(); if (proc) proc.exitCode = exitCode; + invalidateModule(error); if (error instanceof Error) throw error; const reason = typeof error === 'object' && error !== null ? ((error as any).message ?? (error as any).constructor?.name) @@ -215,9 +216,9 @@ function callWasm(fn: () => number): number { // 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'); + const error = new Error('libpg_query ran out of WASM memory (heap limit is WASM_MAXIMUM_MEMORY, 1 GiB); parse large inputs in smaller pieces'); + invalidateModule(error); + return error; } function throwIfErrorString(resultStr: string): void { @@ -228,7 +229,10 @@ function throwIfErrorString(resultStr: string): void { } function ensureLoaded() { - if (!wasmModule) throw new Error("WASM module not initialized. Call `loadModule()` first."); + if (wasmModule) return; + if (memoryLimitError) throw memoryLimitError; + if (!compiledWasm) throw new Error("WASM module not initialized. Call `loadModule()` first."); + wasmModule = createSync(compiledWasm); } type WasmCompiledModule = typeof globalThis extends { @@ -250,20 +254,21 @@ export interface LoadModuleOptions { export async function loadModule(...args: [options?: LoadModuleOptions]): Promise { const wasm = args[0]?.wasm; if (wasm !== undefined) { - provided = wasm instanceof WebAssembly.Module + const module = wasm instanceof WebAssembly.Module ? wasm : await WebAssembly.compile(wasm as ArrayBuffer | ArrayBufferView); // An instance loaded from the file, or still loading, is replaced by one from `wasm`. await loading?.catch(() => {}); - stale = true; + wasmModule = createSync(module); + compiledWasm = module; } - while (!wasmModule || stale) await instantiate(); + while (!wasmModule) await instantiate(); } function awaitInit Promise>(fn: T): T { return (async (...args: Parameters) => { // Re-checked after every await: another call may have failed in between. - while (!wasmModule || stale) await instantiate(); + while (!wasmModule) await instantiate(); return fn(...args); }) as T; } @@ -435,9 +440,7 @@ export const normalize = awaitInit(async (query: string): Promise => { // Sync versions export function parseSync(query: string): ParseResult { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } + ensureLoaded(); // Input validation if (query === null || query === undefined) { @@ -502,9 +505,6 @@ export function parseSync(query: string): ParseResult { } export function parsePlPgSQLSync(query: string): ParseResult { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } const queryPtr = stringToPtr(query); const failuresBefore = failures; let resultPtr = 0; @@ -531,9 +531,6 @@ export function parsePlPgSQLSync(query: string): ParseResult { } export function fingerprintSync(query: string): string { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } const queryPtr = stringToPtr(query); const failuresBefore = failures; let resultPtr = 0; @@ -556,9 +553,6 @@ export function fingerprintSync(query: string): string { } export function normalizeSync(query: string): string { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } const queryPtr = stringToPtr(query); const failuresBefore = failures; let resultPtr = 0; @@ -603,9 +597,6 @@ export const scan = awaitInit(async (query: string): Promise => { }); export function scanSync(query: string): ScanResult { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } const queryPtr = stringToPtr(query); const failuresBefore = failures; let resultPtr = 0; diff --git a/templates/full/pre.js b/templates/full/pre.js new file mode 100644 index 00000000..15689de0 --- /dev/null +++ b/templates/full/pre.js @@ -0,0 +1,23 @@ +// Keep Emscripten's compiled module so recovery uses its original asset load. +if (!Module['compiledWasm']) { + var instantiateFromAsset = instantiateAsync; + instantiateAsync = async (...args) => { + var result = await instantiateFromAsset(...args); + Module['compiledWasm'] = result.module; + return result; + }; +} else { + Module['instantiateWasm'] = (imports, receive) => { + try { + receive(new WebAssembly.Instance(Module['compiledWasm'], imports)); + // This build has no main or startup hooks. Initialize libc and stdio + // now, then skip the deferred run() so it cannot initialize them twice. + initRuntime(); + run = () => {}; + Module['readySync'] = true; + } catch (error) { + Module['initError'] = error; + throw error; + } + }; +} diff --git a/versions/18/src/index.ts b/versions/18/src/index.ts index 5082f7f9..1f6434c2 100644 --- a/versions/18/src/index.ts +++ b/versions/18/src/index.ts @@ -124,6 +124,7 @@ export function formatSqlError( import PgQueryModule from './libpg-query.js'; interface WasmModule { + compiledWasm: WasmCompiledModule; _malloc: (size: number) => number; _free: (ptr: number) => void; _wasm_free_string: (ptr: number) => void; @@ -142,49 +143,34 @@ interface WasmModule { } let wasmModule: WasmModule; - -// After a WASM call throws, the instance is stale: async calls wait for its -// replacement, while sync calls, which cannot wait, keep using it until the -// replacement is ready. One replacement loads at a time; the next call retries -// a failed load. -let stale = false; +let compiledWasm: WasmCompiledModule | undefined; let loading: Promise | undefined; -// Counts WASM calls that threw, so cleanup skips an instance that threw mid-call. +// Invalidation skips cleanup through pointers that belong to a failed instance. let failures = 0; -// Sync calls stop using a stale instance after this many failures on it: past -// about 45, a stack overflow can make the next one spin forever. -const MAX_STALE_FAILURES = 10; -let staleFailures = 0; -// Set by loadModule({ wasm }); instances are then created from it instead of the file. -let provided: WasmCompiledModule | undefined; - -function createModule(): Promise { - const module = provided; - if (!module) return PgQueryModule(); - return new Promise((resolve, reject) => { - PgQueryModule({ - instantiateWasm(imports: any, receive: (instance: any) => void) { - WebAssembly.instantiate(module, imports).then(receive, reject); - return {}; - }, - }).then(resolve, reject); - }); +// Dropped instances can remain live until the current synchronous run yields. +const LARGE_HEAP_BYTES = 512 * 1024 * 1024; +let largeFailures = 0; +let memoryLimitError: Error | undefined; + +function createSync(module: WasmCompiledModule): WasmModule { + const options: Partial & { readySync?: boolean; initError?: unknown } = { + compiledWasm: module, + }; + PgQueryModule(options).catch(() => {}); + if (!options.readySync) { + throw new Error('Could not start a fresh WASM instance', { cause: options.initError }); + } + return options as WasmModule; } function instantiate(): Promise { if (loading) return loading; - const promise = createModule().then( - (module: WasmModule) => { - wasmModule = module; - stale = false; - staleFailures = 0; - loading = undefined; - }, - (error: unknown) => { - loading = undefined; - throw error; + const promise = Promise.resolve().then(async () => { + if (!wasmModule) { + wasmModule = compiledWasm ? createSync(compiledWasm) : await PgQueryModule(); + compiledWasm = wasmModule.compiledWasm; } - ); + }).finally(() => { loading = undefined; }); loading = promise; // Rejects only for the callers awaiting it. promise.catch(() => {}); @@ -193,6 +179,24 @@ function instantiate(): Promise { instantiate(); +function invalidateModule(error: unknown): void { + if (wasmModule.HEAPU8.length > LARGE_HEAP_BYTES) { + if (++largeFailures === 1) { + queueMicrotask(() => { + largeFailures = 0; + memoryLimitError = undefined; + }); + } else { + memoryLimitError = new Error( + 'WASM memory limit hit repeatedly in one synchronous run; yield (await) before retrying', + { cause: error } + ); + } + } + failures++; + wasmModule = undefined; +} + // An exception out of a WASM call (V8 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. @@ -202,11 +206,8 @@ function callWasm(fn: () => number): number { try { return fn(); } catch (error) { - failures++; - stale = true; - if (++staleFailures >= MAX_STALE_FAILURES) wasmModule = undefined; - instantiate(); if (proc) proc.exitCode = exitCode; + invalidateModule(error); if (error instanceof Error) throw error; const reason = typeof error === 'object' && error !== null ? ((error as any).message ?? (error as any).constructor?.name) @@ -222,9 +223,9 @@ function callWasm(fn: () => number): number { // 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'); + const error = new Error('libpg_query ran out of WASM memory (heap limit is WASM_MAXIMUM_MEMORY, 1 GiB); parse large inputs in smaller pieces'); + invalidateModule(error); + return error; } function throwIfErrorString(resultStr: string): void { @@ -235,7 +236,10 @@ function throwIfErrorString(resultStr: string): void { } function ensureLoaded() { - if (!wasmModule) throw new Error("WASM module not initialized. Call `loadModule()` first."); + if (wasmModule) return; + if (memoryLimitError) throw memoryLimitError; + if (!compiledWasm) throw new Error("WASM module not initialized. Call `loadModule()` first."); + wasmModule = createSync(compiledWasm); } type WasmCompiledModule = typeof globalThis extends { @@ -257,20 +261,21 @@ export interface LoadModuleOptions { export async function loadModule(...args: [options?: LoadModuleOptions]): Promise { const wasm = args[0]?.wasm; if (wasm !== undefined) { - provided = wasm instanceof WebAssembly.Module + const module = wasm instanceof WebAssembly.Module ? wasm : await WebAssembly.compile(wasm as ArrayBuffer | ArrayBufferView); // An instance loaded from the file, or still loading, is replaced by one from `wasm`. await loading?.catch(() => {}); - stale = true; + wasmModule = createSync(module); + compiledWasm = module; } - while (!wasmModule || stale) await instantiate(); + while (!wasmModule) await instantiate(); } function awaitInit Promise>(fn: T): T { return (async (...args: Parameters) => { // Re-checked after every await: another call may have failed in between. - while (!wasmModule || stale) await instantiate(); + while (!wasmModule) await instantiate(); return fn(...args); }) as T; } @@ -442,9 +447,7 @@ export const normalize = awaitInit(async (query: string): Promise => { // Sync versions export function parseSync(query: string): ParseResult { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } + ensureLoaded(); // Input validation if (query === null || query === undefined) { @@ -509,9 +512,6 @@ export function parseSync(query: string): ParseResult { } export function parsePlPgSQLSync(query: string): ParseResult { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } const queryPtr = stringToPtr(query); const failuresBefore = failures; let resultPtr = 0; @@ -538,9 +538,6 @@ export function parsePlPgSQLSync(query: string): ParseResult { } export function fingerprintSync(query: string): string { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } const queryPtr = stringToPtr(query); const failuresBefore = failures; let resultPtr = 0; @@ -563,9 +560,6 @@ export function fingerprintSync(query: string): string { } export function normalizeSync(query: string): string { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } const queryPtr = stringToPtr(query); const failuresBefore = failures; let resultPtr = 0; @@ -610,9 +604,6 @@ export const scan = awaitInit(async (query: string): Promise => { }); export function scanSync(query: string): ScanResult { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } const queryPtr = stringToPtr(query); const failuresBefore = failures; let resultPtr = 0; diff --git a/versions/18/src/pre.js b/versions/18/src/pre.js index c2ec5361..9528edf5 100644 --- a/versions/18/src/pre.js +++ b/versions/18/src/pre.js @@ -12,3 +12,27 @@ // `loadModule({ wasm })` can use the bytes it was given. if (ENVIRONMENT_IS_NODE && typeof __dirname == 'undefined') ENVIRONMENT_IS_NODE = false; if (ENVIRONMENT_IS_WORKER && !globalThis.self?.location) ENVIRONMENT_IS_WORKER = false; + +// Keep Emscripten's compiled module so recovery uses its original asset load. +if (!Module['compiledWasm']) { + var instantiateFromAsset = instantiateAsync; + instantiateAsync = async (...args) => { + var result = await instantiateFromAsset(...args); + Module['compiledWasm'] = result.module; + return result; + }; +} else { + Module['instantiateWasm'] = (imports, receive) => { + try { + receive(new WebAssembly.Instance(Module['compiledWasm'], imports)); + // This build has no main or startup hooks. Initialize libc and stdio + // now, then skip the deferred run() so it cannot initialize them twice. + initRuntime(); + run = () => {}; + Module['readySync'] = true; + } catch (error) { + Module['initError'] = error; + throw error; + } + }; +} diff --git a/versions/18/test/load-module.test.js b/versions/18/test/load-module.test.js index 256afd07..9e37311f 100644 --- a/versions/18/test/load-module.test.js +++ b/versions/18/test/load-module.test.js @@ -73,17 +73,21 @@ describe('loadModule({ wasm }) when the wrapper cannot read libpg-query.wasm', { assert.deepEqual(result, { fromModule: 1, fromView: 2 }); }); - it('creates the replacement from the bytes after out-of-memory failures', () => { + it('recovers from supplied bytes and caps repeated OOMs until the caller yields', () => { const result = withoutWasmFile(` await lib.loadModule({ wasm: bytes }); const huge = 'SELECT 1;\\n'.repeat(5000000); const messages = []; - for (let i = 0; i < 3; i++) { + for (let i = 0; i < 2; i++) { try { lib.parseSync(huge); } catch (e) { messages.push(e.message); } } - return { messages, after: (await lib.parse('SELECT 1')).stmts.length }; + let capped; + try { lib.parseSync('SELECT 1'); } catch (e) { capped = e.message; } + return { messages, capped, after: (await lib.parse('SELECT 1')).stmts.length }; `); - assert.equal(result.messages.length, 3); + assert.equal(result.messages.length, 2); + for (const message of result.messages) assert.match(message, /out of WASM memory/); + assert.match(result.capped, /yield \(await\) before retrying/); assert.equal(result.after, 1); }); diff --git a/versions/18/test/wasm-recovery.test.js b/versions/18/test/wasm-recovery.test.js index 48462e16..4aa9d796 100644 --- a/versions/18/test/wasm-recovery.test.js +++ b/versions/18/test/wasm-recovery.test.js @@ -22,9 +22,7 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { assert.equal(parseSync('SELECT 1').stmts.length, 1); }); - // 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'. + // PG 18 reports deep nesting as a regular SQL error rather than a WASM trap. it('returns a stack depth error for deeply nested SQL and keeps the instance', async () => { await loadModule(); for (let i = 0; i < 60; i++) { @@ -77,15 +75,15 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { assert.equal(queued.value.stmts.length, 1); }); - it('throws an Error and keeps process.exitCode when the memory limit is hit', async () => { + it('throws an Error and recovers synchronously when the memory limit is hit', () => { const exitCode = process.exitCode; - await assert.rejects(parse('SELECT 1;\n'.repeat(5000000)), (error) => { + assert.throws(() => parseSync('SELECT 1;\n'.repeat(5000000)), (error) => { assert.ok(error instanceof Error); assert.match(error.message, /out of WASM memory/); return true; }); assert.equal(process.exitCode, exitCode); - assert.equal((await parse('SELECT 1')).stmts.length, 1); + assert.equal(parseSync('SELECT 1').stmts.length, 1); }); for (const name of ['parsePlPgSQL', 'fingerprint', 'normalize', 'scan']) { @@ -107,7 +105,7 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { await isolated.loadModule(); isolated.trapNext(); await assert.rejects(isolated.parse('SELECT 1'), RangeError); - await new Promise((resolve) => setImmediate(resolve)); + await assert.rejects(isolated.parse('SELECT 1'), /Could not start a fresh WASM instance/); assert.equal((await isolated.parse('SELECT 1')).stmts.length, 1); assert.equal(loads, 3); }); @@ -118,7 +116,7 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { await isolated.loadModule(); isolated.trapNext(); assert.throws(() => isolated.parseSync('SELECT 1'), RangeError); - await assert.rejects(isolated.loadModule(), /simulated load failure/); + await assert.rejects(isolated.loadModule(), (error) => error.cause?.message === 'simulated load failure'); await isolated.loadModule(); assert.equal(isolated.parseSync('SELECT 1').stmts.length, 1); assert.equal(loads, 3); @@ -139,19 +137,16 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { assert.deepEqual(results, expected); }); - it('retries a failed fresh load on the next failure, for callers that never await', async () => { + it('retries a failed fresh load on the next sync call without awaiting', async () => { let loads = 0; const isolated = loadTrapping(() => ++loads === 2); await isolated.loadModule(); isolated.trapNext(); assert.throws(() => isolated.parseSync('SELECT 1'), RangeError); - await new Promise((resolve) => setImmediate(resolve)); + assert.throws(() => isolated.parseSync('SELECT 1'), (error) => error.cause?.message === 'simulated load failure'); assert.equal(loads, 2); - 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); + assert.equal(loads, 3); }); it('makes loadModule() wait again when a queued call breaks the fresh instance', async () => { @@ -196,9 +191,8 @@ describe('Recovery from a throw in each entry point', { timeout: 120000 }, () => let used; let frees = 0; let throwNext; - const isolated = loadIsolated(async (real, ...args) => { + const isolated = loadIsolated((module) => { const id = ++loads; - const module = await real(...args); const free = module._free; module._free = (ptr) => { frees++; @@ -215,7 +209,6 @@ describe('Recovery from a throw in each entry point', { timeout: 120000 }, () => throw thrown; }; } - return module; }); async function failOnce(name, query, thrown) { @@ -227,7 +220,8 @@ describe('Recovery from a throw in each entry point', { timeout: 120000 }, () => throwNext = thrown; let caught; try { - await isolated[name](query); + if (name.endsWith('Sync')) isolated[name](query); + else await isolated[name](query); } catch (error) { caught = error; } finally { @@ -236,45 +230,28 @@ describe('Recovery from a throw in each entry point', { timeout: 120000 }, () => } assert.equal(exitCodeAfter, 0, `${name} changed process.exitCode`); assert.equal(frees, freesBefore, `${name} freed memory in the instance that threw`); - assert.equal(loads, loadsBefore + 1, `${name} did not start a fresh instance`); const stale = used; const syncName = name.endsWith('Sync') ? name : 'parseSync'; - assert.ok(isolated[syncName](query), `${syncName} failed while the fresh instance loads`); - assert.equal(used, stale, 'a sync call did not run on the stale instance'); + assert.ok(isolated[syncName](query), `${syncName} failed immediately after a trap`); + assert.notEqual(used, stale, 'a sync call ran on the failed instance'); + assert.equal(loads, loadsBefore + 1, 'expected exactly one replacement'); assert.ok(frees > freesBefore, 'a successful call did not free its memory'); - // A sync caller gets the fresh instance once it awaits loadModule(); async calls wait by themselves. - if (name.endsWith('Sync')) await isolated.loadModule(); assert.ok(await isolated[name](query), `${name} failed after recovery`); assert.equal(used, loads, `${name} ran on the stale instance, not the fresh one`); return caught; } - it('starts one fresh instance for many failures in one synchronous loop', async () => { + it('replaces each failed instance in one synchronous loop', async () => { await isolated.loadModule(); const loadsBefore = loads; - for (let i = 0; i < 5; i++) { - throwNext = new RangeError('Maximum call stack size exceeded'); - assert.throws(() => isolated.parseSync('SELECT 1'), RangeError); - } - assert.equal(loads, loadsBefore + 1); - await isolated.loadModule(); - assert.ok(isolated.parseSync('SELECT 1')); - assert.equal(used, loads); - }); - - it('stops sync calls on a stale instance after 10 failures until the fresh one loads', async () => { - await isolated.loadModule(); - for (let i = 0; i < 9; i++) { + for (let i = 0; i < 60; i++) { throwNext = new RangeError('Maximum call stack size exceeded'); assert.throws(() => isolated.parseSync('SELECT 1'), RangeError); + const failed = used; + assert.equal(isolated.parseSync('SELECT 1').stmts.length, 1); + assert.notEqual(used, failed); } - assert.ok(isolated.parseSync('SELECT 1')); - throwNext = new RangeError('Maximum call stack size exceeded'); - assert.throws(() => isolated.parseSync('SELECT 1'), RangeError); - assert.throws(() => isolated.parseSync('SELECT 1'), /Call `?loadModule\(\)`? first/); - await isolated.loadModule(); - assert.ok(isolated.parseSync('SELECT 1')); - assert.equal(used, loads); + assert.equal(loads, loadsBefore + 60); }); it('makes loadModule() and queued calls wait again when a queued call breaks the fresh instance', async () => { @@ -335,28 +312,39 @@ describe('Recovery from a throw in each entry point', { timeout: 120000 }, () => // 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 isolated = loadIsolated((module) => { 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; - }); + }, failLoad); isolated.trapNext = () => { trap = true; }; return isolated; } // A copy of the wrapper whose WASM factory is wrapped, leaving the shared copy alone. -function loadIsolated(wrapFactory) { +function loadIsolated(decorate, failLoad = () => false) { const indexPath = require.resolve('../wasm/index.cjs'); const factory = require.cache[require.resolve('../wasm/libpg-query.js')]; const shared = require.cache[indexPath]; const realFactory = factory.exports; - factory.exports = (...args) => wrapFactory(realFactory, ...args); + factory.exports = (options = {}) => { + if (failLoad()) { + options.initError = new Error('simulated load failure'); + return Promise.reject(options.initError); + } + const loading = realFactory(options); + if (options.readySync) { + decorate(options); + return loading; + } + return loading.then((module) => { + decorate(module); + return module; + }); + }; delete require.cache[indexPath]; try { return require(indexPath); From cbf692f2e9262a9ec9176803dc8309d1c67dbd90 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Tue, 24 Nov 2026 18:12:15 +0000 Subject: [PATCH 3/6] build(wasm): align manual build with the pinned SDK --- .github/workflows/build-wasm-no-docker.yaml | 6 +++--- templates/full/pre.js | 2 +- versions/18/src/pre.js | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/build-wasm-no-docker.yaml b/.github/workflows/build-wasm-no-docker.yaml index 4cbceebb..a23faffb 100644 --- a/.github/workflows/build-wasm-no-docker.yaml +++ b/.github/workflows/build-wasm-no-docker.yaml @@ -37,10 +37,10 @@ jobs: run: | sudo apt-get update sudo apt-get install cmake python3 python3-pip - git clone --branch 3.1.59 --depth 1 https://github.com/emscripten-core/emsdk.git + git clone --branch 6.0.3 --depth 1 https://github.com/emscripten-core/emsdk.git cd emsdk - ./emsdk install 3.1.59 - ./emsdk activate 3.1.59 + ./emsdk install 6.0.3 + ./emsdk activate 6.0.3 source ./emsdk_env.sh working-directory: versions/18 - name: Build with Emscripten 🏗 diff --git a/templates/full/pre.js b/templates/full/pre.js index 15689de0..55c16c03 100644 --- a/templates/full/pre.js +++ b/templates/full/pre.js @@ -1,4 +1,4 @@ -// Keep Emscripten's compiled module so recovery uses its original asset load. +// Keep the module from the pinned Emscripten factory's own asset load. if (!Module['compiledWasm']) { var instantiateFromAsset = instantiateAsync; instantiateAsync = async (...args) => { diff --git a/versions/18/src/pre.js b/versions/18/src/pre.js index 9528edf5..0ea6f2c2 100644 --- a/versions/18/src/pre.js +++ b/versions/18/src/pre.js @@ -13,7 +13,7 @@ if (ENVIRONMENT_IS_NODE && typeof __dirname == 'undefined') ENVIRONMENT_IS_NODE = false; if (ENVIRONMENT_IS_WORKER && !globalThis.self?.location) ENVIRONMENT_IS_WORKER = false; -// Keep Emscripten's compiled module so recovery uses its original asset load. +// Keep the module from the pinned Emscripten factory's own asset load. if (!Module['compiledWasm']) { var instantiateFromAsset = instantiateAsync; instantiateAsync = async (...args) => { From b7ddfbc603d2d06f0a878ad6aaae20502f2e4ad3 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Tue, 24 Nov 2026 18:14:49 +0000 Subject: [PATCH 4/6] fix(wasm): release failed PG 18 heaps when callers retain errors --- templates/full/index.ts | 16 ++++++++++++---- versions/18/src/index.ts | 16 ++++++++++++---- versions/18/test/wasm-recovery.test.js | 15 ++++++++++----- 3 files changed, 34 insertions(+), 13 deletions(-) diff --git a/templates/full/index.ts b/templates/full/index.ts index 5edd4d17..01f3ff84 100644 --- a/templates/full/index.ts +++ b/templates/full/index.ts @@ -200,15 +200,23 @@ function callWasm(fn: () => number): number { return fn(); } catch (error) { if (proc) proc.exitCode = exitCode; - invalidateModule(error); - if (error instanceof Error) throw error; + if (error instanceof Error) { + invalidateModule(error); + throw error; + } const reason = typeof error === 'object' && error !== null ? ((error as any).message ?? (error as any).constructor?.name) : error; - throw new Error( + // Emscripten's ExitStatus keeps its loader closure and WASM heap alive. + const cause = typeof error === 'object' && error !== null && 'name' in error && error.name === 'ExitStatus' + ? { ...error } + : error; + const wrapped = new Error( `libpg_query terminated (${reason}), most likely out of WASM memory; parse large inputs in smaller pieces`, - { cause: error } + { cause } ); + invalidateModule(wrapped); + throw wrapped; } } diff --git a/versions/18/src/index.ts b/versions/18/src/index.ts index 1f6434c2..f66f6655 100644 --- a/versions/18/src/index.ts +++ b/versions/18/src/index.ts @@ -207,15 +207,23 @@ function callWasm(fn: () => number): number { return fn(); } catch (error) { if (proc) proc.exitCode = exitCode; - invalidateModule(error); - if (error instanceof Error) throw error; + if (error instanceof Error) { + invalidateModule(error); + throw error; + } const reason = typeof error === 'object' && error !== null ? ((error as any).message ?? (error as any).constructor?.name) : error; - throw new Error( + // Emscripten's ExitStatus keeps its loader closure and WASM heap alive. + const cause = typeof error === 'object' && error !== null && 'name' in error && error.name === 'ExitStatus' + ? { ...error } + : error; + const wrapped = new Error( `libpg_query terminated (${reason}), most likely out of WASM memory; parse large inputs in smaller pieces`, - { cause: error } + { cause } ); + invalidateModule(wrapped); + throw wrapped; } } diff --git a/versions/18/test/wasm-recovery.test.js b/versions/18/test/wasm-recovery.test.js index 4aa9d796..06517c00 100644 --- a/versions/18/test/wasm-recovery.test.js +++ b/versions/18/test/wasm-recovery.test.js @@ -31,7 +31,7 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { assert.equal(parseSync('SELECT 1').stmts.length, 1); }); - it('frees each replaced instance, so WASM memory stays at one instance', () => { + it('frees replaced WASM heaps even when callers keep the errors', () => { const script = `const lib = require(${JSON.stringify(require.resolve('../wasm/index.cjs'))}); (async () => { await lib.loadModule(); @@ -44,14 +44,18 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { await lib.loadModule(); } const huge = 'SELECT 1;\\n'.repeat(5000000); - for (let i = 0; i < 2; i++) { - try { await lib.parse(huge); } catch {} + const errors = []; + for (const fn of [lib.parse, lib.normalizeSync]) { + try { await fn(huge); } catch (error) { errors.push(error); } } await lib.loadModule(); lib.parseSync('SELECT 1'); // V8 frees a dropped instance's memory on a later task, not in the same microtask run. await new Promise((resolve) => setTimeout(resolve, 0)); gc(); gc(); + if (errors.length !== 2 || errors.some((error) => !error.message.includes('out of WASM memory'))) { + throw new Error('Expected two WASM memory failures'); + } process.stdout.write('\\ngrown=' + (process.memoryUsage().external - base)); })();`; // A non-zero exit code (libpg_query's exit() leaking out) makes execFileSync throw. @@ -61,7 +65,7 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { stdio: ['ignore', 'pipe', 'ignore'], }); const grown = Number(output.match(/^grown=(-?\d+)$/m)?.[1]); - assert.ok(grown < 32 * 1024 * 1024, `WASM memory grew by ${grown} bytes after 32 replacements`); + assert.ok(grown < 32 * 1024 * 1024, `WASM memory grew by ${grown} bytes after recovery`); }); it('lets a call queued behind a failing one wait for the fresh instance', async () => { @@ -302,7 +306,8 @@ describe('Recovery from a throw in each entry point', { timeout: 120000 }, () => const caught = await failOnce(name, query, thrown); assert.ok(caught instanceof Error); assert.match(caught.message, /out of WASM memory/); - assert.equal(caught.cause, thrown); + assert.notEqual(caught.cause, thrown); + assert.deepEqual(caught.cause, thrown); }); } }); From b535594dc07428d3791563a54d70f7fc0596ef12 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Tue, 24 Nov 2026 18:19:36 +0000 Subject: [PATCH 5/6] fix(wasm): let async recovery yield after a large heap failure --- templates/full/index.ts | 9 ++++++++- versions/18/src/index.ts | 9 ++++++++- versions/18/test/wasm-recovery.test.js | 8 +++++--- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/templates/full/index.ts b/templates/full/index.ts index 01f3ff84..08a9f2f3 100644 --- a/templates/full/index.ts +++ b/templates/full/index.ts @@ -144,6 +144,7 @@ let failures = 0; const LARGE_HEAP_BYTES = 512 * 1024 * 1024; let largeFailures = 0; let memoryLimitError: Error | undefined; +let largeHeapYield: Promise | undefined; function createSync(module: WasmCompiledModule): WasmModule { const options: Partial & { readySync?: boolean; initError?: unknown } = { @@ -158,7 +159,7 @@ function createSync(module: WasmCompiledModule): WasmModule { function instantiate(): Promise { if (loading) return loading; - const promise = Promise.resolve().then(async () => { + const promise = (largeHeapYield ?? Promise.resolve()).then(async () => { if (!wasmModule) { wasmModule = compiledWasm ? createSync(compiledWasm) : await PgQueryModule(); compiledWasm = wasmModule.compiledWasm; @@ -174,6 +175,11 @@ instantiate(); function invalidateModule(error: unknown): void { if (wasmModule.HEAPU8.length > LARGE_HEAP_BYTES) { + // Async callers can give V8 a task to release the dropped heap before allocating again. + largeHeapYield ??= new Promise((resolve) => setTimeout(() => { + largeHeapYield = undefined; + resolve(); + }, 0)); if (++largeFailures === 1) { queueMicrotask(() => { largeFailures = 0; @@ -267,6 +273,7 @@ export async function loadModule(...args: [options?: LoadModuleOptions]): Promis : await WebAssembly.compile(wasm as ArrayBuffer | ArrayBufferView); // An instance loaded from the file, or still loading, is replaced by one from `wasm`. await loading?.catch(() => {}); + if (largeHeapYield) await largeHeapYield; wasmModule = createSync(module); compiledWasm = module; } diff --git a/versions/18/src/index.ts b/versions/18/src/index.ts index f66f6655..6c65165b 100644 --- a/versions/18/src/index.ts +++ b/versions/18/src/index.ts @@ -151,6 +151,7 @@ let failures = 0; const LARGE_HEAP_BYTES = 512 * 1024 * 1024; let largeFailures = 0; let memoryLimitError: Error | undefined; +let largeHeapYield: Promise | undefined; function createSync(module: WasmCompiledModule): WasmModule { const options: Partial & { readySync?: boolean; initError?: unknown } = { @@ -165,7 +166,7 @@ function createSync(module: WasmCompiledModule): WasmModule { function instantiate(): Promise { if (loading) return loading; - const promise = Promise.resolve().then(async () => { + const promise = (largeHeapYield ?? Promise.resolve()).then(async () => { if (!wasmModule) { wasmModule = compiledWasm ? createSync(compiledWasm) : await PgQueryModule(); compiledWasm = wasmModule.compiledWasm; @@ -181,6 +182,11 @@ instantiate(); function invalidateModule(error: unknown): void { if (wasmModule.HEAPU8.length > LARGE_HEAP_BYTES) { + // Async callers can give V8 a task to release the dropped heap before allocating again. + largeHeapYield ??= new Promise((resolve) => setTimeout(() => { + largeHeapYield = undefined; + resolve(); + }, 0)); if (++largeFailures === 1) { queueMicrotask(() => { largeFailures = 0; @@ -274,6 +280,7 @@ export async function loadModule(...args: [options?: LoadModuleOptions]): Promis : await WebAssembly.compile(wasm as ArrayBuffer | ArrayBufferView); // An instance loaded from the file, or still loading, is replaced by one from `wasm`. await loading?.catch(() => {}); + if (largeHeapYield) await largeHeapYield; wasmModule = createSync(module); compiledWasm = module; } diff --git a/versions/18/test/wasm-recovery.test.js b/versions/18/test/wasm-recovery.test.js index 06517c00..5b496d82 100644 --- a/versions/18/test/wasm-recovery.test.js +++ b/versions/18/test/wasm-recovery.test.js @@ -44,11 +44,13 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { await lib.loadModule(); } const huge = 'SELECT 1;\\n'.repeat(5000000); + let yielded = false; + setTimeout(() => { yielded = true; }, 0); const errors = []; - for (const fn of [lib.parse, lib.normalizeSync]) { - try { await fn(huge); } catch (error) { errors.push(error); } - } + try { await lib.parse(huge); } catch (error) { errors.push(error); } await lib.loadModule(); + if (!yielded) throw new Error('Async recovery did not yield after a large heap failure'); + try { lib.normalizeSync(huge); } catch (error) { errors.push(error); } lib.parseSync('SELECT 1'); // V8 frees a dropped instance's memory on a later task, not in the same microtask run. await new Promise((resolve) => setTimeout(resolve, 0)); From 77f37514ebbd3823a2ae56d8c698057a2ca4100d Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Tue, 24 Nov 2026 18:32:48 +0000 Subject: [PATCH 6/6] fix(wasm): honor heap yields requested after recovery is queued --- templates/full/index.ts | 3 ++- versions/18/src/index.ts | 3 ++- versions/18/test/wasm-recovery.test.js | 25 +++++++++++++++++++++---- 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/templates/full/index.ts b/templates/full/index.ts index 08a9f2f3..480fa1a9 100644 --- a/templates/full/index.ts +++ b/templates/full/index.ts @@ -159,7 +159,8 @@ function createSync(module: WasmCompiledModule): WasmModule { function instantiate(): Promise { if (loading) return loading; - const promise = (largeHeapYield ?? Promise.resolve()).then(async () => { + const promise = Promise.resolve().then(async () => { + while (!wasmModule && largeHeapYield) await largeHeapYield; if (!wasmModule) { wasmModule = compiledWasm ? createSync(compiledWasm) : await PgQueryModule(); compiledWasm = wasmModule.compiledWasm; diff --git a/versions/18/src/index.ts b/versions/18/src/index.ts index 6c65165b..26c04561 100644 --- a/versions/18/src/index.ts +++ b/versions/18/src/index.ts @@ -166,7 +166,8 @@ function createSync(module: WasmCompiledModule): WasmModule { function instantiate(): Promise { if (loading) return loading; - const promise = (largeHeapYield ?? Promise.resolve()).then(async () => { + const promise = Promise.resolve().then(async () => { + while (!wasmModule && largeHeapYield) await largeHeapYield; if (!wasmModule) { wasmModule = compiledWasm ? createSync(compiledWasm) : await PgQueryModule(); compiledWasm = wasmModule.compiledWasm; diff --git a/versions/18/test/wasm-recovery.test.js b/versions/18/test/wasm-recovery.test.js index 5b496d82..c56ca03a 100644 --- a/versions/18/test/wasm-recovery.test.js +++ b/versions/18/test/wasm-recovery.test.js @@ -81,6 +81,22 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { assert.equal(queued.value.stmts.length, 1); }); + it('waits for a large heap when sync parsing fails after async recovery is queued', async () => { + const isolated = loadTrapping(); + await isolated.loadModule(); + isolated.trapNext(); + assert.throws(() => isolated.parseSync('SELECT 1'), RangeError); + const queued = isolated.parse('SELECT 1'); + + let yielded = false; + setTimeout(() => { yielded = true; }, 0); + isolated.trapNext(1024 ** 3); + assert.throws(() => isolated.parseSync('SELECT 1'), RangeError); + + assert.equal((await queued).stmts.length, 1); + assert.equal(yielded, true, 'async recovery skipped the large-heap yield'); + }); + it('throws an Error and recovers synchronously when the memory limit is hit', () => { const exitCode = process.exitCode; assert.throws(() => parseSync('SELECT 1;\n'.repeat(5000000)), (error) => { @@ -318,16 +334,17 @@ describe('Recovery from a throw in each entry point', { timeout: 120000 }, () => // 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; + let trapHeapSize; const isolated = loadIsolated((module) => { const parseRaw = module._wasm_parse_query_raw; module._wasm_parse_query_raw = (...callArgs) => { - if (!trap) return parseRaw(...callArgs); - trap = false; + if (trapHeapSize === undefined) return parseRaw(...callArgs); + if (trapHeapSize) module.HEAPU8 = { length: trapHeapSize }; + trapHeapSize = undefined; throw new RangeError('Maximum call stack size exceeded'); }; }, failLoad); - isolated.trapNext = () => { trap = true; }; + isolated.trapNext = (heapSize = 0) => { trapHeapSize = heapSize; }; return isolated; }