Repository navigation
Description
postgres 3.4.9 (the same cachedError() is on master). Reproduced on Node.js 24.22.1, 26.12.1 and 26.0.0, with PostgreSQL 17. Node 24.22.1 and 26.12.1 already include nodejs/node#53443, the fix behind nodejs/node#66129, so this is not that Node bug (see "Related" below).
This is a memory-retention bug, not a security issue: the growth is bounded by the number of sql`…` call sites in the application.
What happens
src/query.js caches one Error per tagged-template call site, so that a failing query can append its origin to error.stack:
const originCache = new Map()
// …
this[originError] = this.handler.debug
? new Error()
: this.tagged && cachedError(this.strings)
// …
function cachedError(xs) {
if (originCache.has(xs))
return originCache.get(xs)
const x = Error.stackTraceLimit
Error.stackTraceLimit = 4
originCache.set(xs, new Error())
Error.stackTraceLimit = x
return originCache.get(xs)
}V8 doesn't format error.stack when the Error is created. It formats it the first time .stack is read.
Until then, the error keeps its structured stack frames:
- each frame holds the
JSFunctionof the frame; - that function holds its closure context;
- the frame that calls
sql`…`is usually a closure inside a request handler.
So the first execution of every call site pins whatever that handler invocation had in scope. It stays pinned as long as originCache lives, which is the life of the process.
.stack is read only if a query from that call site fails. Most call sites never fail, so their errors are never formatted.
The growth is bounded by the number of call sites, so it shows up as a step after the first run of a code path, not as a slope. That makes it easy to mistake for a cache. In a long-running service whose handlers load large data sets and query from helper closures, one request's worth of data per call site stays in the heap until a restart. Full GCs then have that much more to mark.
The retaining path in a heap snapshot (repro.mjs, Node 24.22.1):
(module context of src/query.js) —context originCache→ Map —table→ Error —<symbol>→ array
—internal→ CallSiteInfo —hidden→ closure lookup —context→ Context —context state→ RequestState
On Node 26.12.1 the snapshot shows no CallSiteInfo node; the frame array holds the closure directly. The retention is the same:
… Map —table→ Error —<symbol>→ array —internal→ closure lookup —context→ Context —context state→ RequestState
Reproduction
repro.mjs (full script at the end of this issue) depends only on postgres and a reachable Postgres server. Every query it runs is select $1. A handler builds a 15 MB object, and a helper closure over that object runs one query:
async function handler() {
const state = new RequestState() // ~15 MB
const lookup = (id) => sql`select ${id}::int as id, ${state.rows.length}::int as n`
await lookup(1)
}The script runs this handler in three fresh processes:
- unpatched: postgres as installed.
- workaround: the handler reads
query.originright after creating the query. - patched: a copy of the installed
src/with the fix below applied.
After handler() returns, each process runs six explicit gc() rounds separated by setImmediate, then measures heapUsed and takes a heap snapshot. The heap snapshot is the primary evidence of reachability.
npm i postgres@3.4.9
node repro.mjs postgres://user@127.0.0.1:5432/db
Output: two runs each on Node 24.22.1, 26.12.1 and 26.0.0 (PostgreSQL 17). The numbers are identical on all three:
postgres 3.4.9, node v24.22.1
unpatched : heapUsed after the handler returned and GC: +15.3 MB (the handler's state is 15.3 MB); RequestState reachable: YES
retained by:
…
—context originCache→ object Map
—internal table→ array
—internal 9→ object Error
—property <symbol>→ array
—internal 3→ hidden system / CallSiteInfo
—hidden [2]→ closure lookup
—internal context→ object system / Context
—context state→ object RequestState
origin of a failing query from the same call site: at bad (repro.mjs:108:26)
workaround: heapUsed after the handler returned and GC: +0 MB (the handler's state is 15.3 MB); RequestState reachable: no
origin of a failing query from the same call site: at bad (repro.mjs:108:26)
patched : heapUsed after the handler returned and GC: +0 MB (the handler's state is 15.3 MB); RequestState reachable: no
origin of a failing query from the same call site: at bad (repro.mjs:108:26)
origin line identical in all three: yes
Impact in practice
We found this in a production Node 24 service that runs a nightly bulk import.
In production: after the import, the old-generation space measured right after full GCs stayed at about 1.2–1.3 GB until the next restart. A fresh process sits at about 0.13 GB. Full GCs over that heap paused the main thread for 1–1.4 s.
On a staging reproduction (synthetic data, measured as heapUsed after GC; not directly comparable to the production figure):
| Warm-up | Import 1 | Import 2 | Import 3 | |
|---|---|---|---|---|
| Unpatched | 264 MB | 558 MB | 705 MB | 705 MB |
| With the workaround below | 105 MB | 107 MB | 107 MB | 107 MB |
The unpatched heap grows in steps as new call sites run, then plateaus.
Proposed fix
Format the stack inside cachedError() before caching the error. The same hunk applies to src/query.js, cjs/src/query.js, deno/src/query.js and cf/src/query.js:
const x = Error.stackTraceLimit
Error.stackTraceLimit = 4
- originCache.set(xs, new Error())
+ const error = new Error()
Error.stackTraceLimit = x
- return originCache.get(xs)
+ // Format the stack now. Until .stack is read V8 keeps the structured call sites,
+ // and they hold the calling functions with their closures (whatever the caller
+ // had in scope) for as long as this cache lives, which is the life of the process.
+ // The frames were captured by new Error() under the limit of 4; formatting them
+ // captures nothing new, so the limit is already restored when a user-defined
+ // Error.prepareStackTrace runs here.
+ try { error.stack } catch {} // a throwing Error.prepareStackTrace leaves it as before
+ originCache.set(xs, error)
+ return error
}- Origin text: unchanged. The frames are captured at the same moment as before; V8 only turns them into a string earlier. The repro shows the same origin line with and without the patch.
Error.stackTraceLimit: the patch restores the caller's value right afternew Error(), before the stack is formatted.- The depth of 4 is fixed when the frames are captured.
- So a user-defined
Error.prepareStackTracenever runs while the global limit is temporarily 4.
- Applies cleanly to the v3.4.9 tag and to current
master(git apply --check). - Cost: one stack format of at most four frames per call site, once per process. A cache hit costs nothing new.
- The cache exists to avoid creating an
Errorper query (Expensive instantiation of Errors to capture stack traces? #290), and the patch keeps that. - In our benchmark, query construction costs about 0.2 µs more (the user-land workaround below, measured with and without). The first query from each new call site costs about 4 µs more, once per process. End-to-end p50/p95/p99 latency of 50k queries showed no measurable difference.
- The cache exists to avoid creating an
debug: true: not affected. It creates a freshErrorper query, which is collected together with the query.- A throwing
Error.prepareStackTrace: the read is wrapped intry, so creating a query never throws because of it. Such an error stays unformatted, as today.
An alternative is to cache the formatted string instead of the Error. There is already an originStackCache for that.
Workaround until then
Read query.origin once after creating a tagged query (sql`…`). That formats the cached error, and it's what the "workaround" run does. The catch is that this has to happen for every tagged query, including fragments that are never sent on their own.
Only tagged queries have a cached error, so skip queries without a template (unsafe(), file()).
The user-land equivalent we use is an accessor for the OriginError symbol on Query.prototype:
- the symbol is read from
Object.getOwnPropertySymbols()of any tagged query; - the accessor's setter stores the value and reads
.stack; - this works because the constructor assigns
this[originError], rather than defining it as a class field.
Related
- Expensive instantiation of Errors to capture stack traces? #290 (2022): the cost of creating an
Errorper query to capture stack traces. Caching oneErrorper call site is the answer to that, and this retention is its side effect. The proposed fix keeps the caching. - Query errors get a read-only
stackon Node 22+ #1227: query errors get a read-onlystackon Node 22+. It's a different issue in howqueryError()appends the origin, and it is unaffected by this change. - An
Errorcreated inside asetImmediatecallback retains theImmediate, its AsyncLocalStorage store, and — via stale_idleNext/_idlePrevlinks — the stores of every Immediate that ran in the same tick nodejs/node#66129: an independent confirmation of the V8 behaviour this relies on. There, anErrorwhose stack was never read keeps its frames (and through them, execution context) alive, and reading.stackreleases them.- It was closed as a duplicate. Its
setImmediate/AsyncLocalStorage amplification was fixed by timers: do not retain a reference to the async store after firing nodejs/node#53443, which shipped in 24.20.0 and 26.6.0. - The underlying behaviour, frames kept until
.stackis read, is how V8 works and is unchanged. - The repro above runs on versions that include timers: do not retain a reference to the async store after firing nodejs/node#53443.
- It was closed as a duplicate. Its
repro.mjs
// Minimal reproduction: postgres.js keeps the closure of the first caller of every
// sql`…` call site alive for the life of the process.
//
// Depends only on the `postgres` package (tested with 3.4.9) and a Postgres you can
// connect to. Nothing is created in the database: the queries are `select $1`.
//
// npm i postgres@3.4.9
// node repro.mjs postgres://user@127.0.0.1:5432/db
//
// It runs the same request handler three times, each in a fresh child process:
// unpatched — postgres as installed
// workaround — the handler reads `query.origin` right after creating the query
// patched — a copy of the installed postgres/src with cachedError() formatting
// the stack before caching it (the proposed fix above)
// and reports, after the handler has returned and several full GCs, how much of the
// heap is still in use and whether the handler's state is reachable in a heap
// snapshot (with the retaining path when it is).
import { spawnSync } from 'node:child_process'
import { cpSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import v8 from 'node:v8'
import vm from 'node:vm'
const url = process.argv[2] || process.env.DATABASE_URL
const mode = process.argv[3]
if (!url) {
console.error('usage: node repro.mjs postgres://user@host:port/db')
process.exit(1)
}
if (!mode) parent()
else await child(mode)
function parent() {
const pkgDir = dirname(dirname(fileURLToPath(import.meta.resolve('postgres'))))
const { version } = JSON.parse(readFileSync(join(pkgDir, 'package.json'), 'utf8'))
console.log(`postgres ${version}, node ${process.version}`)
const results = {}
for (const m of ['unpatched', 'workaround', 'patched']) {
const r = spawnSync(process.execPath, [fileURLToPath(import.meta.url), url, m], { encoding: 'utf8' })
if (r.status !== 0) { console.log(r.stdout + r.stderr); process.exit(1) }
const out = JSON.parse(r.stdout.trim().split('\n').pop())
results[m] = out
console.log(`\n${m.padEnd(10)}: heapUsed after the handler returned and GC: ${out.deltaMB >= 0 ? '+' : ''}${out.deltaMB} MB `
+ `(the handler's state is ${out.stateMB} MB); RequestState reachable: ${out.reachable ? 'YES' : 'no'}`)
if (out.path) console.log(' retained by:\n' + out.path)
console.log(` origin of a failing query from the same call site: ${out.callerLine}`)
}
const same = results.unpatched.callerLine === results.patched.callerLine && results.unpatched.callerLine === results.workaround.callerLine
console.log(`\norigin line identical in all three: ${same ? 'yes' : 'NO'}`)
}
async function child(mode) {
v8.setFlagsFromString('--expose-gc')
const gc = vm.runInNewContext('gc')
const settle = async () => {
for (let i = 0; i < 6; i++) { gc(); await new Promise((r) => setImmediate(r)) }
return process.memoryUsage().heapUsed
}
let entry = fileURLToPath(import.meta.resolve('postgres')) // …/postgres/src/index.js (the ESM build)
let tmp = null
if (mode === 'patched') {
// the proposed fix, applied to a copy of the installed ESM sources
tmp = mkdtempSync(join(tmpdir(), 'pg-origin-'))
cpSync(dirname(entry), join(tmp, 'src'), { recursive: true })
writeFileSync(join(tmp, 'package.json'), '{"type":"module"}')
const file = join(tmp, 'src', 'query.js')
// the same change as the proposed fix: the limit goes back right after new Error(), then the stack is read
const before = ' originCache.set(xs, new Error())\n Error.stackTraceLimit = x\n return originCache.get(xs)\n'
const after = ' const error = new Error()\n Error.stackTraceLimit = x\n try { error.stack } catch {}\n originCache.set(xs, error)\n return error\n'
const src = readFileSync(file, 'utf8')
if (!src.includes(before)) throw new Error('cachedError() is not the one this patch was written for')
writeFileSync(file, src.replace(before, after))
entry = join(tmp, 'src', 'index.js')
}
const { default: postgres } = await import(pathToFileURL(entry).href)
const sql = postgres(url, { max: 1, onnotice: () => {} })
await sql`select 1 as warm`
class RequestState {
constructor() { this.rows = Array.from({ length: 2_000_000 }, (_, i) => i) } // ~15 MB
}
// A request handler: it loads some state, and a helper closure over that state
// runs a query. Nothing outside the handler keeps a reference to the state.
async function handler() {
const state = new RequestState()
const lookup = (id) => sql`select ${id}::int as id, ${state.rows.length}::int as n`
const query = lookup(1)
if (mode === 'workaround') void query.origin
await query
}
const base = await settle()
await handler()
const after = await settle()
// heap snapshot: is a RequestState reachable from the GC roots, and through what?
const file = v8.writeHeapSnapshot(join(tmpdir(), `pg-origin-${process.pid}.heapsnapshot`))
const found = reachable(JSON.parse(readFileSync(file, 'utf8')), 'RequestState')
rmSync(file)
// the origin text a failing query gets, from a call site created the same way
let callerLine = ''
async function failing() {
const state = new RequestState()
const bad = () => sql`select ${state.rows.length}::int / 0 as boom`
try { await bad() } catch (e) { callerLine = e.stack.split('\n').find((l) => l.includes('repro.mjs')).trim() }
}
await failing()
await sql.end()
if (tmp) rmSync(tmp, { recursive: true, force: true })
console.log(JSON.stringify({
mode,
deltaMB: Number(((after - base) / 1048576).toFixed(1)),
stateMB: Number((2_000_000 * 8 / 1048576).toFixed(1)),
reachable: found.reachable,
path: found.path,
callerLine: callerLine.replace(/\(.*[/\\]/, '('),
}))
}
// Shortest path from the GC roots to an object of the given constructor name, over
// strong edges only (what "Retainers" in Chrome DevTools shows).
function reachable(snap, name) {
const m = snap.snapshot.meta
const NF = m.node_fields.length, EF = m.edge_fields.length
const nType = m.node_fields.indexOf('type'), nName = m.node_fields.indexOf('name'), nEdges = m.node_fields.indexOf('edge_count')
const eType = m.edge_fields.indexOf('type'), eName = m.edge_fields.indexOf('name_or_index'), eTo = m.edge_fields.indexOf('to_node')
const nodeTypes = m.node_types[0], edgeTypes = m.edge_types[0]
const { nodes, edges, strings } = snap
const count = nodes.length / NF
const first = new Uint32Array(count + 1)
for (let i = 0, e = 0; i < count; i++) { first[i] = e; e += nodes[i * NF + nEdges] * EF }
first[count] = edges.length
const prev = new Int32Array(count).fill(-1), via = new Int32Array(count).fill(-1)
const queue = [0]
prev[0] = 0
let target = -1
for (let h = 0; h < queue.length && target < 0; h++) {
const i = queue[h]
for (let e = first[i]; e < first[i + 1]; e += EF) {
if (edgeTypes[edges[e + eType]] === 'weak') continue
const to = edges[e + eTo] / NF
if (prev[to] !== -1) continue
prev[to] = i; via[to] = e; queue.push(to)
if (nodeTypes[nodes[to * NF + nType]] === 'object' && strings[nodes[to * NF + nName]] === name) { target = to; break }
}
}
if (target < 0) return { reachable: false, path: null }
const lines = []
for (let i = target; i !== 0; i = prev[i]) {
const e = via[i], t = edgeTypes[edges[e + eType]]
const edge = t === 'element' || t === 'hidden' ? `[${edges[e + eName]}]` : strings[edges[e + eName]]
lines.push(` —${t} ${edge}→ ${nodeTypes[nodes[i * NF + nType]]} ${String(strings[nodes[i * NF + nName]]).slice(0, 60)}`)
}
return { reachable: true, path: lines.reverse().join('\n') }
}
Activity
porsager commentedon Oct 29, 2026
Fixed in v4: only the trimmed stack text is kept per template, not the
Errorand its call sites, so the closure that made a query can be collected. There's a test for it.tests: use vitest's test() and expect() in transactions, connection, …