Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(postgres-driver): a closed connection forgets its last written statement; pin each retention with a driver e2e test

garrytan7111b89c134e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c6d45a668a..dd83716b06 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,12 +20,13 @@ identifiers and attribution are available in the pre-removal Git revision
|---|---|---|
| A pooled Postgres connection after a query whose reply spanned several network reads | kept the joined receive buffer (about 2 MiB for a 1 MiB `bytea` row, which arrives as hex) until its next read | drops the buffer once every message in it is handled |
| A pooled Postgres connection after any query | kept the whole query, and through it the query's full result rows, for the desync tripwire's diagnostic | keeps only the statement's text, which is all the diagnostic prints |
-| Reading a segmented page body on a pool of 4 | up to about 12 MiB held after the read finished (one segment's buffer and rows per connection) | about 1 MiB of ordinary heap noise |
+| A pooled Postgres connection that closed under a statement (a terminated backend, a pooler restart, a stuck or desynced connection) | kept that statement, with its parameters, until the pool gave the connection another one | keeps nothing |
+| Reading a segmented page body on a pool of 4 | up to about 12 MiB held after the read finished (one segment's buffer and rows per connection) | 1 to 2 MiB of ordinary heap noise |
### For contributors
-- `vendor/postgres` (ESM, CommonJS and workerd copies) and `patches/[email protected]` carry both changes; `bash vendor/update-postgres.sh --check` verifies them, and `vendor/README.md` describes them.
-- `test/large-pages/segmented-prior-view.test.ts` stops flaking on the Postgres arm. Its heap check failed in about one run in ten (5.8 MiB held against a 5.5 MiB bound) because the warm-up and the measured call left driver buffers on different pooled connections. The test now runs one small statement on every pooled connection before its baseline, so a driver that keeps a read fails it every run. The bound is unchanged.
+- `vendor/postgres` (ESM, CommonJS and workerd copies) and `patches/[email protected]` carry the three changes; `bash vendor/update-postgres.sh --check` verifies them, and `vendor/README.md` describes them. `test/e2e/postgres-driver-idle-retention-postgres.test.ts` pins each one: a 4 MiB row or parameter leaves under 2 MiB behind, where the old driver kept 4 to 12 MiB.
+- `test/large-pages/segmented-prior-view.test.ts` stops flaking on the Postgres arm. Its heap check failed now and then (5.8 MiB held against a 5.5 MiB bound) because the warm-up and the measured call left driver buffers on different pooled connections. The test now runs one small statement on every pooled connection before its baseline, so a driver that keeps its receive buffers fails it every run. The bound is unchanged.
## [0.60.309.0] - 2026-10-19
diff --git a/patches/[email protected] b/patches/[email protected]
index 254ec5c740..929c9c631c 100644
--- a/patches/[email protected]
+++ b/patches/[email protected]
@@ -1,5 +1,5 @@
diff --git a/cjs/src/connection.js b/vendor/postgres/cjs/src/connection.js
-index 07f6716..5a7b7eb 100644
+index 07f6716..c329876 100644
--- a/cjs/src/connection.js
+++ b/vendor/postgres/cjs/src/connection.js
@@ -20,6 +20,7 @@ const Sync = b().S().end()
@@ -301,9 +301,11 @@ index 07f6716..5a7b7eb 100644
function queryError(query, err) {
if (query.reserve)
return query.reject(err)
-@@ -438,19 +597,47 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -437,20 +596,49 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ incoming = Buffer.alloc(0)
remaining = 0
incomings = null
++ lastWritten = null
clearImmediate(nextWriteTimer)
+ // GBrain (#6355): bytes still waiting for the cleared immediate belonged to this socket. Left in place, the next
+ // connection's StartupMessage is appended to them and never scheduled for writing (the timer handle is not
@@ -350,7 +352,7 @@ index 07f6716..5a7b7eb 100644
closedTime = performance.now()
hadError && options.shared.retries++
delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000
-@@ -459,6 +646,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -459,6 +647,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
/* Handlers */
function handle(xs, x = xs[0]) {
@@ -361,7 +363,7 @@ index 07f6716..5a7b7eb 100644
(
x === 68 ? DataRow : // D
x === 100 ? CopyData : // d
-@@ -489,6 +680,39 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -489,6 +681,39 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
)(xs)
}
@@ -401,7 +403,7 @@ index 07f6716..5a7b7eb 100644
function DataRow(x) {
let index = 7
let length
-@@ -533,13 +757,25 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -533,13 +758,25 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
}
function ReadyForQuery(x) {
@@ -428,7 +430,7 @@ index 07f6716..5a7b7eb 100644
} else {
query.resolve(results || result)
}
-@@ -547,9 +783,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -547,9 +784,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
errored(errorResponse)
}
@@ -445,7 +447,7 @@ index 07f6716..5a7b7eb 100644
if (initial) {
if (target_session_attrs) {
-@@ -564,23 +807,43 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -564,23 +808,43 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
return fetchArrayTypes()
}
@@ -495,7 +497,7 @@ index 07f6716..5a7b7eb 100644
: connection.reserved()
: ending
? terminate()
-@@ -630,7 +893,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -630,7 +894,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))
query.prepare && (statements[query.signature] = query.statement)
@@ -507,7 +509,7 @@ index 07f6716..5a7b7eb 100644
}
function RowDescription(x) {
-@@ -767,14 +1034,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -767,14 +1035,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
async function fetchArrayTypes() {
needsTypes = false
@@ -537,7 +539,7 @@ index 07f6716..5a7b7eb 100644
types.forEach(({ oid, typarray }) => addArrayType(oid, typarray))
}
-@@ -821,7 +1095,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -821,7 +1096,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
function retry(q, error) {
delete statements[q.signature]
q.retried = error
@@ -555,7 +557,7 @@ index 07f6716..5a7b7eb 100644
}
function NotificationResponse(x) {
-@@ -1039,6 +1322,59 @@ function xor(a, b) {
+@@ -1039,6 +1323,59 @@ function xor(a, b) {
return buffer
}
@@ -1117,7 +1119,7 @@ index 0578284..e80a868 100644
return '$' + (types.push(
diff --git a/src/connection.js b/vendor/postgres/src/connection.js
-index 1b1cccd..65ce1f6 100644
+index 1b1cccd..75e3eba 100644
--- a/src/connection.js
+++ b/vendor/postgres/src/connection.js
@@ -20,6 +20,7 @@ const Sync = b().S().end()
@@ -1419,9 +1421,11 @@ index 1b1cccd..65ce1f6 100644
function queryError(query, err) {
if (query.reserve)
return query.reject(err)
-@@ -438,19 +597,47 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -437,20 +596,49 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+ incoming = Buffer.alloc(0)
remaining = 0
incomings = null
++ lastWritten = null
clearImmediate(nextWriteTimer)
+ // GBrain (#6355): bytes still waiting for the cleared immediate belonged to this socket. Left in place, the next
+ // connection's StartupMessage is appended to them and never scheduled for writing (the timer handle is not
@@ -1468,7 +1472,7 @@ index 1b1cccd..65ce1f6 100644
closedTime = performance.now()
hadError && options.shared.retries++
delay = (typeof backoff === 'function' ? backoff(options.shared.retries) : backoff) * 1000
-@@ -459,6 +646,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -459,6 +647,10 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
/* Handlers */
function handle(xs, x = xs[0]) {
@@ -1479,7 +1483,7 @@ index 1b1cccd..65ce1f6 100644
(
x === 68 ? DataRow : // D
x === 100 ? CopyData : // d
-@@ -489,6 +680,39 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -489,6 +681,39 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
)(xs)
}
@@ -1519,7 +1523,7 @@ index 1b1cccd..65ce1f6 100644
function DataRow(x) {
let index = 7
let length
-@@ -533,13 +757,25 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -533,13 +758,25 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
}
function ReadyForQuery(x) {
@@ -1546,7 +1550,7 @@ index 1b1cccd..65ce1f6 100644
} else {
query.resolve(results || result)
}
-@@ -547,9 +783,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -547,9 +784,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
errored(errorResponse)
}
@@ -1563,7 +1567,7 @@ index 1b1cccd..65ce1f6 100644
if (initial) {
if (target_session_attrs) {
-@@ -564,23 +807,43 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -564,23 +808,43 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
return fetchArrayTypes()
}
@@ -1613,7 +1617,7 @@ index 1b1cccd..65ce1f6 100644
: connection.reserved()
: ending
? terminate()
-@@ -630,7 +893,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -630,7 +894,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
!query.statement.types[i] && (query.statement.types[i] = x.readUInt32BE(7 + i * 4))
query.prepare && (statements[query.signature] = query.statement)
@@ -1625,7 +1629,7 @@ index 1b1cccd..65ce1f6 100644
}
function RowDescription(x) {
-@@ -767,14 +1034,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -767,14 +1035,21 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
async function fetchArrayTypes() {
needsTypes = false
@@ -1655,7 +1659,7 @@ index 1b1cccd..65ce1f6 100644
types.forEach(({ oid, typarray }) => addArrayType(oid, typarray))
}
-@@ -821,7 +1095,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
+@@ -821,7 +1096,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
function retry(q, error) {
delete statements[q.signature]
q.retried = error
@@ -1673,7 +1677,7 @@ index 1b1cccd..65ce1f6 100644
}
function NotificationResponse(x) {
-@@ -1039,6 +1322,59 @@ function xor(a, b) {
+@@ -1039,6 +1323,59 @@ function xor(a, b) {
return buffer
}
diff --git a/test/e2e/postgres-driver-idle-retention-postgres.test.ts b/test/e2e/postgres-driver-idle-retention-postgres.test.ts
new file mode 100644
index 0000000000..485357f3e8
--- /dev/null
+++ b/test/e2e/postgres-driver-idle-retention-postgres.test.ts
@@ -0,0 +1,63 @@
+/**
+ * An idle pooled connection keeps nothing from its last statement. Stock postgres.js left its receive buffer as an
+ * empty view over the last message it joined from several socket reads, so a large row's DataRow (twice the row's bytes
+ * for a bytea, which arrives as hex) stayed allocated until the connection's next read; and the desync tripwire kept the
+ * last query, whose promise holds its result rows. A pool hands statements out in turn, so each connection held one.
+ *
+ * A connection that closed under a statement also kept that statement (and its parameters) as the last one written.
+ *
+ * Regression that fails it on the base driver: after a 4 MiB bytea read whose result is dropped, the heap holds the
+ * 8 MiB DataRow (receive buffer) and the 4 MiB decoded row (tripwire); either one alone is over the 2 MiB bound. After
+ * a statement with a 4 MiB parameter whose backend is terminated, the closed connection holds the parameter.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import postgres from '#postgres';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
+
+const url = process.env.DATABASE_URL;
+const MB = 1024 * 1024;
+const ROW = 4 * MB;
+const opened: Array<{ end: (o?: { timeout?: number }) => Promise<void> }> = [];
+afterEach(async () => { while (opened.length) await opened.pop()!.end({ timeout: 1 }).catch(() => {}); });
+
+function heap(): number {
+ Bun.gc(true);
+ return process.memoryUsage().heapUsed;
+}
+
+describe.skipIf(!url)('vendored driver retention after a large row', () => {
+ test('a connection keeps neither the receive buffer nor the rows of its last statement', async () => {
+ assertSafeE2eDatabaseUrl(url!);
+ const sql = postgres(url!, { max: 1, onnotice: () => {} });
+ opened.push(sql);
+ await sql.unsafe('SELECT 1');
+ const base = heap();
+ const read = async () => {
+ const [row] = await sql.unsafe("SELECT decode(repeat('ab', $1::int), 'hex') AS body", [ROW]) as unknown as Array<{ body: Uint8Array }>;
+ return row!.body.length;
+ };
+ expect(await read()).toBe(ROW);
+ await new Promise(resolve => setTimeout(resolve, 0));
+ const held = heap() - base;
+ console.log('[postgres-driver-retention] held ' + (held / MB).toFixed(2) + ' MiB after a ' + ROW / MB + ' MiB bytea row');
+ expect(held).toBeLessThan(ROW / 2);
+ });
+
+ test('a connection that closed under a statement keeps neither the statement nor its parameters', async () => {
+ assertSafeE2eDatabaseUrl(url!);
+ const sql = postgres(url!, { max: 1, onnotice: () => {} });
+ const admin = postgres(url!, { max: 1, onnotice: () => {} });
+ opened.push(sql, admin);
+ const [{ pid }] = await sql.unsafe('SELECT pg_backend_pid() AS pid') as unknown as Array<{ pid: number }>;
+ const base = heap();
+ const settled = Promise.resolve(sql.unsafe('SELECT pg_sleep(30), length($1::bytea)', [Buffer.alloc(ROW, 1)]))
+ .then(() => 'resolved', (e: { code?: string }) => e.code ?? 'error');
+ await new Promise(resolve => setTimeout(resolve, 500));
+ await admin.unsafe('SELECT pg_terminate_backend($1)', [pid]);
+ expect(await settled).not.toBe('resolved');
+ await new Promise(resolve => setTimeout(resolve, 0));
+ const held = heap() - base;
+ console.log('[postgres-driver-retention] held ' + (held / MB).toFixed(2) + ' MiB after a closed statement with a ' + ROW / MB + ' MiB parameter');
+ expect(held).toBeLessThan(ROW / 2);
+ });
+});
diff --git a/vendor/README.md b/vendor/README.md
index ecbd5a5d5e..117975a21f 100644
--- a/vendor/README.md
+++ b/vendor/README.md
@@ -95,9 +95,11 @@ left its receive buffer as an empty view over the last message it joined from
several socket reads, so the buffer stayed allocated until the connection's
next read. For a 1 MiB bytea row, that buffer is the 2 MiB hex DataRow. The
desync tripwire keeps only the last statement's text, not the query, whose
-promise holds its rows. Pools hand statements out in turn, so before this fix
-each pooled connection held one segment read
-(`test/large-pages/segmented-prior-view.test.ts`).
+promise holds its rows, and a connection that closes forgets the last
+statement it wrote, with its parameters. Pools hand statements out in turn, so
+before this fix each pooled connection held one segment read
+(`test/e2e/postgres-driver-idle-retention-postgres.test.ts`,
+`test/large-pages/segmented-prior-view.test.ts`).
## Reproduce and update
diff --git a/vendor/postgres/cf/src/connection.js b/vendor/postgres/cf/src/connection.js
index 56bac11cc4..526b51e0eb 100644
--- a/vendor/postgres/cf/src/connection.js
+++ b/vendor/postgres/cf/src/connection.js
@@ -598,6 +598,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
incoming = Buffer.alloc(0)
remaining = 0
incomings = null
+ lastWritten = null
clearImmediate(nextWriteTimer)
// GBrain (#6355): bytes still waiting for the cleared immediate belonged to this socket. Left in place, the next
// connection's StartupMessage is appended to them and never scheduled for writing (the timer handle is not
diff --git a/vendor/postgres/cjs/src/connection.js b/vendor/postgres/cjs/src/connection.js
index 5a7b7eb9ba..c329876649 100644
--- a/vendor/postgres/cjs/src/connection.js
+++ b/vendor/postgres/cjs/src/connection.js
@@ -596,6 +596,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
incoming = Buffer.alloc(0)
remaining = 0
incomings = null
+ lastWritten = null
clearImmediate(nextWriteTimer)
// GBrain (#6355): bytes still waiting for the cleared immediate belonged to this socket. Left in place, the next
// connection's StartupMessage is appended to them and never scheduled for writing (the timer handle is not
diff --git a/vendor/postgres/src/connection.js b/vendor/postgres/src/connection.js
index 65ce1f6aca..75e3ebaabc 100644
--- a/vendor/postgres/src/connection.js
+++ b/vendor/postgres/src/connection.js
@@ -596,6 +596,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
incoming = Buffer.alloc(0)
remaining = 0
incomings = null
+ lastWritten = null
clearImmediate(nextWriteTimer)
// GBrain (#6355): bytes still waiting for the cleared immediate belonged to this socket. Left in place, the next
// connection's StartupMessage is appended to them and never scheduled for writing (the timer handle is not