Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(postgres driver): reject statements issued between a socket error and its close (managed-sync pooler-drop stall)
garrytan000e18e706c9
diff --git a/test/postgres-driver-startup-death.test.ts b/test/postgres-driver-startup-death.test.tsindex 1bf1ead843..add599aa46 100644--- a/test/postgres-driver-startup-death.test.ts+++ b/test/postgres-driver-startup-death.test.ts@@ -32,6 +32,14 @@ class ScriptedSocket extends Socket {this.destroy();for (const listener of listeners) listener(false);}+ /** A connection reset as Bun reports it: 'error' (ECONNRESET), then 'close' with hadError on a later turn. */+ async resetNow(): Promise<void> {+ const errors = this.listeners('error') as ((error: Error) => void)[], closes = this.listeners('close') as ((hadError: boolean) => void)[];+ this.removeAllListeners('error'); this.removeAllListeners('close'); this.on('error', () => undefined); this.destroy();+ for (const listener of errors) listener(Object.assign(new Error('read ECONNRESET'), { code: 'ECONNRESET' }));+ await new Promise(resolve => setImmediate(resolve));+ for (const listener of closes) listener(true);+ }}/** A one-byte type plus int32 length frame of the wire protocol. */@@ -54,27 +62,35 @@ const fatalTerminated = frame('E', Buffer.concat([Buffer.from('M'), cstr('terminating connection due to administrator command'), Buffer.from([0]),]));-type Script = { kill?: boolean; killAt?: number };+type Script = { kill?: boolean; killAt?: number; holdAt?: number };/*** Answers the extended protocol with empty results (ParseComplete, BindComplete, NoData, CommandComplete, ReadyForQuery)* and a simple Query with CommandComplete. `kill` ends the connection with FATAL 57P01 at its first statement, `killAt`- * at its n-th (1-based).+ * at its n-th (1-based), `holdAt` never answers its n-th. ReadyForQuery reports T between a BEGIN and its COMMIT or ROLLBACK.*/-function serve(socket: Socket, buffered: Buffer, mode: Script, onStatement: () => number): Buffer {+function serve(socket: Socket, buffered: Buffer, mode: Script, onStatement: () => number, held = { on: false, tx: false }): Buffer {let rest: Buffer = buffered;for (;;) {if (rest.length < 5) return rest;const type = String.fromCharCode(rest[0]!), length = rest.readInt32BE(1);if (rest.length < length + 1) return rest;+ const body = rest.subarray(5, length + 1);rest = rest.subarray(length + 1);const statement = type === 'P' || type === 'Q' ? onStatement() : 0;+ if (statement > 0) {+ const text = (type === 'P' ? body.subarray(body.indexOf(0) + 1) : body).toString('utf8').toLowerCase();+ held.tx = /^\s*begin/.test(text) || (held.tx && !/^\s*(commit|rollback)/.test(text));+ }+ const ready = held.tx ? frame('Z', Buffer.from('T')) : readyForQuery;if (mode.kill || (statement > 0 && statement === mode.killAt)) { socket.write(fatalTerminated); socket.end(); return Buffer.alloc(0); }+ if (statement > 0) held.on = statement === mode.holdAt;+ if (held.on) continue;if (type === 'P') socket.write(frame('1'));else if (type === 'B') socket.write(frame('2'));else if (type === 'D') socket.write(frame('n'));else if (type === 'E') socket.write(frame('C', cstr('SELECT 0')));- else if (type === 'S') socket.write(readyForQuery);- else if (type === 'Q') socket.write(Buffer.concat([frame('C', cstr('SELECT 0')), readyForQuery]));+ else if (type === 'S') socket.write(ready);+ else if (type === 'Q') socket.write(Buffer.concat([frame('C', cstr('SELECT 0')), ready]));else if (type === 'X') { socket.end(); return Buffer.alloc(0); }}}@@ -90,6 +106,7 @@ async function listen(script: (connection: number) => Script): Promise<{ port: nconnections.push(connection);const mode = script(connections.length);let buffered: Buffer = Buffer.alloc(0), started = false;+ const held = { on: false, tx: false };socket.on('data', (chunk: Buffer) => {buffered = Buffer.concat([buffered, chunk]);if (!started) {@@ -99,7 +116,7 @@ async function listen(script: (connection: number) => Script): Promise<{ port: nbuffered = buffered.subarray(length); started = true;socket.write(startupReply);}- buffered = serve(socket, buffered, mode, () => ++connection.statements);+ buffered = serve(socket, buffered, mode, () => ++connection.statements, held);});socket.on('error', () => undefined);});@@ -175,3 +192,37 @@ test('forced probe (#6543): a backend terminated under a running statement doesexpect(connections[1]!.statements).toBe(1);} finally { await sql.end({ timeout: 1 }); }}, 15_000);++test('forced probe (GBRA-133): a statement a transaction issues between a socket error and its close settles, and the reconnect serves the next reservation', async () => {+ // Managed-sync convergence mode (f): a pooler drop reset the transaction's connection under a running statement. Its+ // rejection ran the coordinated write's finally, which sent the settings restore on the same connection before the+ // socket's 'close' arrived. The close skipped rejecting it (hadError), the replacement socket's startup ReadyForQuery+ // made it the current statement without sending it, and the reservation waiting for that startup never got the+ // connection: the run stalled 330 s until the in-flight watchdog retired it.+ const { port, connections } = await listen(connection => (connection === 1 ? { holdAt: 2 } : {}));+ const { sql, socket } = client(port, { fetch_types: false });+ const within = <T>(promise: Promise<T>, label: string) => Promise.race([promise, Bun.sleep(3_000).then(() => `${label} never settled`)]);+ try {+ let restore: Promise<string | null> | undefined;+ let running!: () => void;+ const started = new Promise<void>(resolve => { running = resolve; });+ const transaction = sql.begin(async tx => {+ const held = tx.unsafe('select 1');+ running();+ await held.catch(() => {+ restore = Promise.resolve(tx.unsafe('select 2')).then(() => null, (error: { code?: string }) => error.code ?? 'error');+ return restore;+ });+ }).then(() => null, (error: { code?: string }) => error.code ?? 'error');+ await started;+ await Bun.sleep(20);+ await socket().resetNow();+ expect(await within(transaction, 'transaction')).toMatch(/^(ECONNRESET|CONNECTION_CLOSED)$/);+ expect(restore).toBeDefined();+ expect(await within(restore!, 'restore')).toBe('CONNECTION_CLOSED');+ const next = await within(sql.reserve().then(async reserved => { try { return [...await reserved.unsafe('select 3')]; } finally { reserved.release(); } }), 'next reservation');+ expect(next).toEqual([]);+ expect(connections.length).toBe(2);+ } finally { await sql.end({ timeout: 1 }); }+}, 15_000);+diff --git a/vendor/postgres/src/connection.js b/vendor/postgres/src/connection.jsindex 28f3e50f98..89345ba83b 100644--- a/vendor/postgres/src/connection.js+++ b/vendor/postgres/src/connection.js@@ -670,7 +670,11 @@ function Connection(options, queues = {}, { onopen = noop, onend = noop, onclose// GBrain (#6543 A6): a socket that closed under statements is a recovery the next completed startup reports.;(query || sent.length) && (recovering = recovering || 'closed')- !hadError && (query || sent.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))+ // GBRA-133: a socket error rejects the statements in flight, but their rejection handlers run before 'close' and may+ // issue more on this connection (a transaction's settings restore in its finally). Skipped on hadError, those stayed+ // queued: the next socket's startup ReadyForQuery made one the current statement without ever sending it, so it hung+ // until the in-flight watchdog (330 s) and the reservation waiting for that startup never got its connection.+ ;(query || sent.length || deferredRetries.length) && error(Errors.connection('CONNECTION_CLOSED', options, socket))// GBrain (#6543): the dead socket's ErrorResponse (a FATAL 57P01, a pooler's XX000) and its partial result belonged// to statements that just failed. Left in place, the replacement connection's startup ReadyForQuery handed that// error to its first statement, and a stale row count left holes at the start of the next result.