Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(postgres-driver): a stale-plan retry waits for a describe-first statement sent after it

garrytan5787fcabbb99
diff --git a/test/e2e/postgres-driver-retry-pipeline.test.ts b/test/e2e/postgres-driver-retry-pipeline.test.ts
new file mode 100644
index 0000000000..891ae62353
--- /dev/null
+++ b/test/e2e/postgres-driver-retry-pipeline.test.ts
@@ -0,0 +1,43 @@
+/**
+ * Vendored driver (vendor/postgres): a prepared statement the server rejects as stale ("cached plan must not
+ * change result type") is re-run by the driver. When a describe-first statement was sent after it on the same
+ * connection, that statement writes its Bind/Execute only once the server answers its Describe, so a retry
+ * written at once landed between the two halves and every later response was read for the wrong query: rows
+ * built with another statement's columns, or a DataRow read before any column list (a TypeError). The retry
+ * now waits for that statement.
+ */
+import { describe, expect, test } from 'bun:test';
+import postgres from '#postgres';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
+
+const databaseUrl = process.env.DATABASE_URL;
+
+describe.skipIf(!databaseUrl)('vendored driver: a stale-plan retry and a describe-first statement on one connection', () => {
+ test('each query reads its own rows across 100 retries pipelined behind describe-first statements', async () => {
+ assertSafeE2eDatabaseUrl(databaseUrl!);
+ const sql = postgres(databaseUrl!, { max: 1, onnotice: () => {} });
+ const suffix = crypto.randomUUID().replace(/-/g, '').slice(0, 12);
+ const wide = `driver_retry_wide_${suffix}`, narrow = `driver_retry_narrow_${suffix}`;
+ try {
+ await sql.unsafe(`CREATE TABLE ${wide} (a int); CREATE TABLE ${narrow} (slug text, k text);
+ INSERT INTO ${wide} VALUES (1); INSERT INTO ${narrow} VALUES ('seed', 'x')`);
+ for (let i = 0; i < 100; i++) {
+ await sql.unsafe(`SELECT * FROM ${wide} WHERE a = $1`, [1], { prepare: true });
+ await sql.unsafe(`ALTER TABLE ${wide} ADD COLUMN c${i} int`);
+ const [stale, first, second] = await Promise.all([
+ sql.unsafe(`SELECT * FROM ${wide} WHERE a = $1`, [1], { prepare: true }),
+ sql.unsafe(`SELECT slug FROM ${narrow} WHERE k = $1 AND ${i} >= 0`, ['x'], { prepare: true }),
+ sql.unsafe(`SELECT slug FROM ${narrow} WHERE k = $1 AND ${i} >= 0`, ['x'], { prepare: true }),
+ ]);
+ expect(Object.keys(stale[0]!)).toHaveLength(i + 2);
+ expect(first.map(row => row.slug)).toEqual(['seed']);
+ expect(first.map(row => Object.keys(row))).toEqual([['slug']]);
+ expect(second.map(row => row.slug)).toEqual(['seed']);
+ expect(second.map(row => Object.keys(row))).toEqual([['slug']]);
+ }
+ } finally {
+ await sql.unsafe(`DROP TABLE IF EXISTS ${wide}; DROP TABLE IF EXISTS ${narrow}`).catch(() => {});
+ await sql.end();
+ }
+ }, 120_000);
+});
diff --git a/vendor/postgres/cf/src/connection.js b/vendor/postgres/cf/src/connection.js
index 4f654a37ab..04deb2cba6 100644
--- a/vendor/postgres/cf/src/connection.js
+++ b/vendor/postgres/cf/src/connection.js
@@ -100,6 +100,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
, rows = 0
, serverSignature = null
, nextWriteTimer = null
+ , lastWritten = null
+ , deferredRetries = []
, terminated = false
, incomings = null
, results = null
@@ -177,6 +179,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
: (query = q, query.active = true)
build(q)
+ lastWritten = q
const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)
return write(toBuffer(q))
&& !q.describeFirst
@@ -400,6 +403,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
errored(err)
while (sent.length)
queryError(sent.shift(), err)
+ while (deferredRetries.length)
+ queryError(deferredRetries.shift(), err)
}
function errored(err) {
@@ -568,6 +573,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
function ReadyForQuery(x) {
connection.status = x[5]
+ query && query === lastWritten && (lastWritten = null)
if (query) {
if (errorResponse) {
// GBrain: a failed statement describes again next time instead of trusting shared parameter types.
@@ -612,6 +618,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))
Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)
+ flushRetries()
+
if (query)
return // Consider opening if able and sent.length < 50
@@ -673,6 +681,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
query.typesKey && query.statement.types.every(t => t > 0 && t < 16384)
&& options.shared_types.set(query.typesKey, query.statement.types.slice())
query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false)
+ flushRetries()
}
function RowDescription(x) {
@@ -870,7 +879,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
function retry(q, error) {
delete statements[q.signature]
q.retried = error
- execute(q)
+ deferredRetries.push(q)
+ flushRetries()
+ }
+
+ // GBrain: a describe-first or cursor query writes its next messages only when the server answers its first
+ // ones. A retry written in that gap lands between them on the wire, and every later response is then read
+ // for the wrong query (rows built with another statement's columns). Retries wait for that query.
+ function flushRetries() {
+ while (deferredRetries.length && !(lastWritten && (lastWritten.describeFirst || lastWritten.cursorFn)))
+ execute(deferredRetries.shift())
}
function NotificationResponse(x) {
diff --git a/vendor/postgres/cjs/src/connection.js b/vendor/postgres/cjs/src/connection.js
index ec88b7ca40..06419b85d6 100644
--- a/vendor/postgres/cjs/src/connection.js
+++ b/vendor/postgres/cjs/src/connection.js
@@ -98,6 +98,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
, rows = 0
, serverSignature = null
, nextWriteTimer = null
+ , lastWritten = null
+ , deferredRetries = []
, terminated = false
, incomings = null
, results = null
@@ -175,6 +177,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
: (query = q, query.active = true)
build(q)
+ lastWritten = q
const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)
return write(toBuffer(q))
&& !q.describeFirst
@@ -398,6 +401,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
errored(err)
while (sent.length)
queryError(sent.shift(), err)
+ while (deferredRetries.length)
+ queryError(deferredRetries.shift(), err)
}
function errored(err) {
@@ -566,6 +571,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
function ReadyForQuery(x) {
connection.status = x[5]
+ query && query === lastWritten && (lastWritten = null)
if (query) {
if (errorResponse) {
// GBrain: a failed statement describes again next time instead of trusting shared parameter types.
@@ -610,6 +616,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))
Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)
+ flushRetries()
+
if (query)
return // Consider opening if able and sent.length < 50
@@ -671,6 +679,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
query.typesKey && query.statement.types.every(t => t > 0 && t < 16384)
&& options.shared_types.set(query.typesKey, query.statement.types.slice())
query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false)
+ flushRetries()
}
function RowDescription(x) {
@@ -868,7 +877,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
function retry(q, error) {
delete statements[q.signature]
q.retried = error
- execute(q)
+ deferredRetries.push(q)
+ flushRetries()
+ }
+
+ // GBrain: a describe-first or cursor query writes its next messages only when the server answers its first
+ // ones. A retry written in that gap lands between them on the wire, and every later response is then read
+ // for the wrong query (rows built with another statement's columns). Retries wait for that query.
+ function flushRetries() {
+ while (deferredRetries.length && !(lastWritten && (lastWritten.describeFirst || lastWritten.cursorFn)))
+ execute(deferredRetries.shift())
}
function NotificationResponse(x) {
diff --git a/vendor/postgres/src/connection.js b/vendor/postgres/src/connection.js
index c4d90e6282..437ecd5ec4 100644
--- a/vendor/postgres/src/connection.js
+++ b/vendor/postgres/src/connection.js
@@ -98,6 +98,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
, rows = 0
, serverSignature = null
, nextWriteTimer = null
+ , lastWritten = null
+ , deferredRetries = []
, terminated = false
, incomings = null
, results = null
@@ -175,6 +177,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
: (query = q, query.active = true)
build(q)
+ lastWritten = q
const mayPipeline = !q.options.onexecute || q.options.onexecute(connection)
return write(toBuffer(q))
&& !q.describeFirst
@@ -398,6 +401,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
errored(err)
while (sent.length)
queryError(sent.shift(), err)
+ while (deferredRetries.length)
+ queryError(deferredRetries.shift(), err)
}
function errored(err) {
@@ -566,6 +571,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
function ReadyForQuery(x) {
connection.status = x[5]
+ query && query === lastWritten && (lastWritten = null)
if (query) {
if (errorResponse) {
// GBrain: a failed statement describes again next time instead of trusting shared parameter types.
@@ -610,6 +616,8 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
while (sent.length && (query = sent.shift()) && (query.active = true, query.cancelled))
Connection(options).cancel(query.state, query.cancelled.resolve, query.cancelled.reject)
+ flushRetries()
+
if (query)
return // Consider opening if able and sent.length < 50
@@ -671,6 +679,7 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
query.typesKey && query.statement.types.every(t => t > 0 && t < 16384)
&& options.shared_types.set(query.typesKey, query.statement.types.slice())
query.describeFirst && !query.onlyDescribe && (write(prepared(query)), query.describeFirst = false)
+ flushRetries()
}
function RowDescription(x) {
@@ -868,7 +877,16 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose
function retry(q, error) {
delete statements[q.signature]
q.retried = error
- execute(q)
+ deferredRetries.push(q)
+ flushRetries()
+ }
+
+ // GBrain: a describe-first or cursor query writes its next messages only when the server answers its first
+ // ones. A retry written in that gap lands between them on the wire, and every later response is then read
+ // for the wrong query (rows built with another statement's columns). Retries wait for that query.
+ function flushRetries() {
+ while (deferredRetries.length && !(lastWritten && (lastWritten.describeFirst || lastWritten.cursorFn)))
+ execute(deferredRetries.shift())
}
function NotificationResponse(x) {