Every failed statement permanently uses up part of the stack-depth budget ("stack depth limit exceeded" after ~1 800 errors)
Version: @electric-sql/pglite 0.5.8
Environment: Node.js v25.6.1, macOS 26.0.1 (darwin-arm64). Seen with both a file-system data directory and memory://.
Summary
Every statement that ends in an ERROR leaves the PGlite instance a little closer to Postgres's stack-depth limit, and this is never given back. After roughly 1 800 failed statements (the exact number depends on the kind of error), every statement on that instance fails with:
error: stack depth limit exceeded
hint: Increase the configuration parameter "max_stack_depth" (currently 2048kB), after ensuring the platform's stack depth limit is adequate.
file: stack_depth.c, line: 104, routine: check_stack_depthThis includes SELECT 1, BEGIN and COMMIT, until the instance is closed and opened again.
Successful statements have no effect. The WASM heap and pg_backend_memory_contexts stay flat while the failures add up, so this does not look like a memory leak; it looks like something on the error path that does not restore what check_stack_depth() measures against.
Minimal reproduction
// npm i @electric-sql/[email protected] && node repro.mjs
import { PGlite } from '@electric-sql/pglite';
const db = await PGlite.create();
for (let i = 1; ; i++) {
try { await db.query('SELECT 1/0'); }
catch (e) {
if (/stack depth limit exceeded/.test(e.message)) { console.log(`exhausted after ${i} failures`); break; }
}
}
await db.query('SELECT 1'); // throws: stack depth limit exceededPrints exhausted after 1873 failures; the final SELECT 1 throws.
// Minimal reproduction: every FAILED statement uses up part of PGlite's Postgres stack-depth budget for good.
// npm i @electric-sql/[email protected] && node pglite-stack-leak-repro.mjs
import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { PGlite } from '@electric-sql/pglite';
/** The installed version (the package does not export its package.json). */
function pgliteVersion() {
let d = dirname(fileURLToPath(import.meta.resolve('@electric-sql/pglite')));
for (let i = 0; i < 5; i++, d = dirname(d)) {
try { const p = JSON.parse(readFileSync(join(d, 'package.json'), 'utf8')); if (p.name === '@electric-sql/pglite') return p.version; } catch {}
}
return '?';
}
const version = pgliteVersion();
const isStackDepth = (e) => /stack depth limit exceeded/.test(String(e?.message));
/** Runs `failing` until any statement fails with "stack depth limit exceeded"; returns how many failures that took. */
async function failuresUntilExhausted(db, failing) {
for (let i = 1; i <= 50_000; i++) {
try { await db.query(failing); } catch (e) { if (isStackDepth(e)) return i; }
if (i % 25 === 0) { try { await db.query('SELECT 1'); } catch (e) { if (isStackDepth(e)) return i; throw e; } }
}
return null;
}
const heapMB = (db) => (db.mod?.HEAPU8?.buffer?.byteLength ?? 0) / 1e6;
const memCtx = async (db) => Number((await db.query('SELECT sum(used_bytes)::bigint AS u FROM pg_backend_memory_contexts')).rows[0].u);
console.log(`@electric-sql/pglite ${version}, node ${process.version}, ${process.platform}-${process.arch}`);
{
const db = await PGlite.create();
console.log(`max_stack_depth = ${(await db.query('SHOW max_stack_depth')).rows[0].max_stack_depth}`);
// Successful statements: no effect.
for (let i = 0; i < 50_000; i++) await db.query('SELECT $1::int + 1', [i]);
console.log(`50 000 successful statements: still fine -> ${(await db.query('SELECT 1 AS ok')).rows[0].ok === 1}`);
await db.close();
}
for (const [name, sql, prep] of [
['division_by_zero', 'SELECT 1/0', null],
['undefined_table', 'SELECT * FROM no_such_table', null],
['unique_violation', 'INSERT INTO t VALUES (1)', 'CREATE TABLE t (id int PRIMARY KEY); INSERT INTO t VALUES (1)'],
]) {
const db = await PGlite.create();
if (prep) await db.exec(prep);
const heap0 = heapMB(db), ctx0 = await memCtx(db);
const n = await failuresUntilExhausted(db, sql);
const per = n ? (2048 / n).toFixed(2) : '-';
console.log(`${name.padEnd(17)} exhausted after ${n} failures (~${per} kB of the 2 MB budget each); wasm heap ${heap0.toFixed(1)} -> ${heapMB(db).toFixed(1)} MB; memory contexts ${ctx0} B before`);
await db.close();
}
{
// Workaround: closing and opening the database again restores it.
const db = await PGlite.create('memory://reopen');
for (let i = 0; i < 1800; i++) await db.query('SELECT 1/0').catch(() => {});
await db.close();
const db2 = await PGlite.create('memory://reopen');
const n = await failuresUntilExhausted(db2, 'SELECT 1/0');
console.log(`after close + reopen: exhausted again only after ${n} more failures`);
await db2.close();
}Measurements
max_stack_depth = 2MB. "Budget per failure" is 2 048 kB divided by the number of failures it took to exhaust it.
| Error | Failures until exhausted | ≈ budget per failure | WASM heap before → after |
|---|---|---|---|
SELECT 1/0 (division_by_zero) |
1 873 | 1.09 kB | 197.7 → 197.7 MB |
SELECT * FROM no_such_table (undefined_table) |
1 796 | 1.14 kB | 197.7 → 197.7 MB |
duplicate-key INSERT (unique_violation) |
2 979 | 0.69 kB | 197.7 → 197.7 MB |
50 000 successful SELECT $1::int + 1 |
never | 0 | flat |
Other observations:
- Deterministic: the same numbers on every run, also in a fresh directory with a fresh install.
- A cliff, not a slope: the deepest nested expression the parser accepts (
SELECT ((((…1))))) does not change until the cliff, so the real stack is not being consumed. What runs out is whatevercheck_stack_depth()compares against. - Close + reopen restores the budget:
close()and a newPGlite.create()on the same data directory need another 1 873 failures to exhaust it again.
Expected vs actual
- Expected: a failed statement is reported to the caller and leaves the instance as it was, as in native Postgres. An instance can run indefinitely whatever mix of successful and failed statements it executes.
- Actual: each failed statement permanently uses up about 0.7–1.1 kB of the 2 MB stack-depth budget. After about 1 800–3 000 failures, every statement fails with "stack depth limit exceeded" until the instance is recreated.
Impact and workaround
A long-running Node process with one open instance stopped working after about 78 minutes. The cause was a query that failed about 24 times a minute and was caught and ignored. We removed the failing query.
As a safety net we now close and reopen the instance after 300 failed statements, at a quiet moment, which takes about 40 ms. Raising max_stack_depth would only move the cliff.
Possibly related: #1071 (sjlj error recovery in the WASI build). This report is about the npm package on Node.
Happy to test a fix or provide more data.
Source: electric-sql/pglite