From bc025ae8c2a10deafc643fab3f0c30bda5c1f31f Mon Sep 17 00:00:00 2001 From: robobun Date: Sun, 16 Aug 2026 19:21:17 +0000 Subject: [PATCH 01/12] sql(postgres): re-prepare cached statements invalidated by 26000/0A000 A named prepared statement that the server invalidates (SQLSTATE 26000 after DEALLOCATE/DISCARD ALL or a pooler swapping the backend; 0A000 "cached plan must not change result type" from RevalidateCachedQuery after DDL such as ALTER TABLE) stayed Prepared in the per-connection statement cache. The ErrorResponse handler only evicted a cache entry when the statement was still Parsing, so every later execution of that query bound the dead server-side name and failed forever. On these errors for an already-Prepared named statement the handler now evicts the cache entry (releasing exactly the map's ref) and, when the failing exchange is the only one in flight, the session is idle (the ReadyForQuery transaction status byte is now tracked on the connection; a retry inside a transaction block would be rejected with 25P02 and mask the original error), and this request has not retried already, resets the statement under a fresh server-side name and re-queues the request so advance() re-Parses it. Otherwise the request is rejected normally but the cache is still evicted, so the next execution succeeds. The 0A000 match is narrowed to routine RevalidateCachedQuery, matching pgjdbc, so an execute-time 0A000 from an FDW or PL/pgSQL is not silently re-executed. Restores TransactionStatusIndicator and ReadyForQuery.status, which were removed as unused; the retry gate depends on them. Co-authored-by: robobun --- src/sql/lib.rs | 2 + src/sql/postgres/PostgresProtocol.rs | 1 + src/sql/postgres/protocol/ErrorResponse.rs | 23 + src/sql/postgres/protocol/ReadyForQuery.rs | 21 +- .../protocol/TransactionStatusIndicator.rs | 11 + src/sql_jsc/postgres/PostgresSQLConnection.rs | 61 ++- src/sql_jsc/postgres/PostgresSQLQuery.rs | 3 + src/sql_jsc/postgres/PostgresSQLStatement.rs | 14 + src/sql_jsc/postgres/Signature.rs | 41 +- ...es-prepared-statement-invalidation.test.ts | 395 ++++++++++++++++++ test/js/sql/sql.test.ts | 14 +- 11 files changed, 549 insertions(+), 37 deletions(-) create mode 100644 src/sql/postgres/protocol/TransactionStatusIndicator.rs create mode 100644 test/js/sql/postgres-prepared-statement-invalidation.test.ts diff --git a/src/sql/lib.rs b/src/sql/lib.rs index 91fd8b659669..6aef9cfd7d74 100644 --- a/src/sql/lib.rs +++ b/src/sql/lib.rs @@ -200,6 +200,8 @@ pub mod postgres { pub mod stack_reader; #[path = "StartupMessage.rs"] pub mod startup_message; + #[path = "TransactionStatusIndicator.rs"] + pub mod transaction_status_indicator; // ── flat re-exports for `bun_sql_jsc` (Decode/Write trait surface) ── pub use new_reader::ReaderContext; diff --git a/src/sql/postgres/PostgresProtocol.rs b/src/sql/postgres/PostgresProtocol.rs index 0608e7cd447d..075a6f5a9f61 100644 --- a/src/sql/postgres/PostgresProtocol.rs +++ b/src/sql/postgres/PostgresProtocol.rs @@ -62,3 +62,4 @@ pub use crate::postgres::protocol::sasl_initial_response::SASLInitialResponse; pub use crate::postgres::protocol::sasl_response::SASLResponse; pub use crate::postgres::protocol::stack_reader::StackReader; pub use crate::postgres::protocol::startup_message::StartupMessage; +pub use crate::postgres::protocol::transaction_status_indicator::TransactionStatusIndicator; diff --git a/src/sql/postgres/protocol/ErrorResponse.rs b/src/sql/postgres/protocol/ErrorResponse.rs index 1181f8437a8e..14d8b9a21753 100644 --- a/src/sql/postgres/protocol/ErrorResponse.rs +++ b/src/sql/postgres/protocol/ErrorResponse.rs @@ -19,6 +19,29 @@ impl fmt::Display for ErrorResponse { } impl ErrorResponse { + /// True when the server-side prepared statement is gone (SQLSTATE `26000`) + /// or its cached plan is stale (SQLSTATE `0A000` from routine + /// `RevalidateCachedQuery`; `0A000` alone is the generic + /// feature_not_supported class). Mirrors pgjdbc `willHealViaReparse`. + pub fn invalidates_prepared_statement(&self) -> bool { + let mut code_26000 = false; + let mut code_0a000 = false; + let mut routine_revalidate = false; + for m in &self.messages { + match m { + FieldMessage::Code(code) => { + code_26000 = code.eql_comptime(b"26000"); + code_0a000 = code.eql_comptime(b"0A000"); + } + FieldMessage::Routine(r) => { + routine_revalidate = r.eql_comptime(b"RevalidateCachedQuery"); + } + _ => {} + } + } + code_26000 || (code_0a000 && routine_revalidate) + } + pub fn decode_internal( mut reader: NewReader, ) -> Result { diff --git a/src/sql/postgres/protocol/ReadyForQuery.rs b/src/sql/postgres/protocol/ReadyForQuery.rs index 50cec26c7fd5..d86f06f5c723 100644 --- a/src/sql/postgres/protocol/ReadyForQuery.rs +++ b/src/sql/postgres/protocol/ReadyForQuery.rs @@ -1,8 +1,18 @@ use super::new_reader::NewReader; +use super::transaction_status_indicator::TransactionStatusIndicator; use crate::postgres::AnyPostgresError; -#[derive(Default)] -pub struct ReadyForQuery {} +pub struct ReadyForQuery { + pub status: TransactionStatusIndicator, +} + +impl Default for ReadyForQuery { + fn default() -> Self { + Self { + status: TransactionStatusIndicator::I, + } + } +} impl ReadyForQuery { pub fn decode_internal( @@ -10,8 +20,9 @@ impl ReadyForQuery { ) -> Result { reader.length()?; - // transaction status indicator - reader.int::()?; - Ok(Self {}) + let status = reader.int::()?; + Ok(Self { + status: TransactionStatusIndicator(status), + }) } } diff --git a/src/sql/postgres/protocol/TransactionStatusIndicator.rs b/src/sql/postgres/protocol/TransactionStatusIndicator.rs new file mode 100644 index 000000000000..10ffba2b28fa --- /dev/null +++ b/src/sql/postgres/protocol/TransactionStatusIndicator.rs @@ -0,0 +1,11 @@ +// Any u8 value is valid storage (the wire can carry bytes outside {I, T, E}). +// A Rust `#[repr(u8)] enum` would be UB for such values, so this is a +// transparent u8 newtype with associated consts instead. +#[repr(transparent)] +#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] +pub struct TransactionStatusIndicator(pub u8); + +impl TransactionStatusIndicator { + /// if idle (not in a transaction block) + pub const I: Self = Self(b'I'); +} diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index f575ab14d4f8..f2cf75580cbb 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -124,6 +124,10 @@ pub struct PostgresSQLConnection { // so `vm_mut()`'s `&mut *as_ptr()` is sound. pub(crate) vm: BackRef, pub(crate) statements: JsCell, + /// Transaction status byte from the last ReadyForQuery; gates the + /// re-prepare retry (a retry inside a transaction block masks 0A000/26000 + /// with 25P02). + pub(crate) tx_status: Cell, pub(crate) prepared_statement_id: Cell, pub(crate) pending_activity_count: AtomicU32, // Self-wrapper back-ref (the JS object that owns this payload). Stored as a @@ -1185,6 +1189,7 @@ pub(crate) fn call(global_object: &JSGlobalObject, callframe: &CallFrame) -> JsR core::ptr::NonNull::new(VirtualMachine::get_mut_ptr()).expect("vm singleton"), ), statements: JsCell::new(PreparedStatementsMap::default()), + tx_status: Cell::new(protocol::TransactionStatusIndicator::I), prepared_statement_id: Cell::new(0), pending_activity_count: AtomicU32::new(0), js_value: JsCell::new(crate::jsc::JsRef::empty()), @@ -2502,7 +2507,8 @@ impl PostgresSQLConnection { // parameter_status dropped at scope end } MessageType::ReadyForQuery => { - let _ready_for_query = protocol::ReadyForQuery::decode_internal(reader.reborrow())?; + let ready_for_query = protocol::ReadyForQuery::decode_internal(reader.reborrow())?; + self.tx_status.set(ready_for_query.status); if self.status.get() != Status::Connected && !matches!(self.authentication_state.get(), AuthenticationState::Ok) @@ -2978,6 +2984,7 @@ impl PostgresSQLConnection { debug!("ErrorResponse: {}", err); return Err(AnyPostgresError::ExpectedRequest); }; + let invalidates = err.invalidates_prepared_statement(); // Convert to JS while we still own `err` — materialize the JS value once and route through // `on_js_error` to avoid double-ownership of the non-Clone ErrorResponse. let js_err = @@ -3003,6 +3010,58 @@ impl PostgresSQLConnection { // held one ref and the request still holds another; cannot drop to 0. unsafe { PostgresSQLStatement::deref(core::ptr::from_mut(stmt)) }; } + } else if stmt.status == StatementStatus::Prepared + && invalidates + && !stmt.signature.prepared_statement_name.is_empty() + { + // Server-side named statement gone or stale: evict so + // later queries with this signature re-prepare. + if let Some(removed) = self + .statements + .with_mut(|m| m.remove(&stmt.signature.name[..])) + { + // SAFETY: releases exactly the map's ref. `removed` + // may differ from `stmt` if user JS inserted a new + // entry between pipelined siblings' ErrorResponses. + unsafe { PostgresSQLStatement::deref(removed) }; + } + // Retry only when no other Bind/Execute responses are + // already on the wire and the session is idle (inside a + // transaction the retry Parse would be rejected 25P02). + if !request.flags.get().reprepared + && self.tx_status.get() == protocol::TransactionStatusIndicator::I + && self.pipelined_requests.get() <= 1 + && self.nonpipelinable_requests.get() == 0 + { + debug!("re-preparing invalidated statement (SQLSTATE {})", err); + self.finish_request(&request); + let id = self.prepared_statement_id.get(); + self.prepared_statement_id.set(id + 1); + stmt.reset_for_reprepare(id); + let slot = self.statements.with_mut(|m| { + m.get_or_put(&stmt.signature.name).map(|e| { + debug_assert!(!e.found_existing); + core::ptr::from_mut::<*mut PostgresSQLStatement>(e.value_ptr) + }) + }); + if let Ok(slot) = slot { + stmt.ref_(); + // SAFETY: map not mutated since `get_or_put`; + // store the root pointer (same provenance as + // `do_run`), not a `&mut`-derived one. + unsafe { *slot = request.statement.get().expect("statement set") }; + } + request.status.set(QueryStatus::Pending); + request.update_flags(|f| { + f.reprepared = true; + f.binary = false; + }); + self.note_request_pending(); + self.update_ref(); + return Ok(()); + } + // Leave the statement Prepared so the last pipelined + // sibling's ErrorResponse can still re-prepare it. } } // If `err` was not moved into stmt above, it drops here automatically. diff --git a/src/sql_jsc/postgres/PostgresSQLQuery.rs b/src/sql_jsc/postgres/PostgresSQLQuery.rs index 54e1e2d1954c..55093e169755 100644 --- a/src/sql_jsc/postgres/PostgresSQLQuery.rs +++ b/src/sql_jsc/postgres/PostgresSQLQuery.rs @@ -94,6 +94,8 @@ pub struct Flags { /// `None` when `finish_request` consumes that contribution, so the /// decrement is idempotent across its call sites. pub(crate) counter: RequestCounter, + /// Set after one transparent re-prepare on 26000/0A000; caps retries at 1. + pub(crate) reprepared: bool, pub(crate) result_mode: PostgresSQLQueryResultMode, } @@ -114,6 +116,7 @@ impl Default for Flags { bigint: false, simple: false, counter: RequestCounter::None, + reprepared: false, result_mode: PostgresSQLQueryResultMode::Objects, } } diff --git a/src/sql_jsc/postgres/PostgresSQLStatement.rs b/src/sql_jsc/postgres/PostgresSQLStatement.rs index 9b867377b475..21dce6fa4653 100644 --- a/src/sql_jsc/postgres/PostgresSQLStatement.rs +++ b/src/sql_jsc/postgres/PostgresSQLStatement.rs @@ -83,6 +83,20 @@ impl PostgresSQLStatement { self.ref_count.set(n); } + /// Reset to pre-Parse state under a fresh server-side name so `advance()` + /// re-Parses after a 26000/0A000 invalidation. + pub(crate) fn reset_for_reprepare(&mut self, prepared_statement_id: u64) { + self.status = Status::Pending; + self.error_response = None; + self.fields = Vec::new(); + self.parameters = Box::default(); + self.cached_structure = PostgresCachedStructure::default(); + self.needs_duplicate_check = true; + self.fields_flags = DataCellFlags::default(); + self.signature + .set_prepared_statement_name(prepared_statement_id); + } + pub(crate) fn check_for_duplicate_fields(&mut self) { if !self.needs_duplicate_check { return; diff --git a/src/sql_jsc/postgres/Signature.rs b/src/sql_jsc/postgres/Signature.rs index a9cbb30fda70..0658f81b9711 100644 --- a/src/sql_jsc/postgres/Signature.rs +++ b/src/sql_jsc/postgres/Signature.rs @@ -19,6 +19,21 @@ impl Signature { // No explicit `Drop` impl needed: the `Box<[T]>` fields free the four owned slices automatically. + /// `P` + 40 bytes of `name` + `$` + up to 20 digits ≤ Postgres' 63-byte + /// identifier limit. + pub(crate) fn set_prepared_statement_name(&mut self, prepared_statement_id: u64) { + use std::io::Write; + let mut v: Vec = Vec::new(); + write!( + &mut v, + "P{}${}", + bstr::BStr::new(&self.name[..self.name.len().min(40)]), + prepared_statement_id, + ) + .expect("unreachable"); + self.prepared_statement_name = v.into_boxed_slice(); + } + // JSError (from QueryBindingIterator / // Tag::from_js), OOM, and InvalidQueryBinding are collapsed to the // crate-wide `crate::Error`. @@ -91,26 +106,14 @@ impl Signature { if iter.any_failed() { return Err(crate::Error::InvalidQueryBinding); } - // max u64 length is 20, max prepared_statement_name length is 63 - let prepared_statement_name: Box<[u8]> = if unnamed { - Box::default() - } else { - use std::io::Write; - let mut v: Vec = Vec::new(); - write!( - &mut v, - "P{}${}", - bstr::BStr::new(&name[..name.len().min(40)]), - prepared_statement_id, - ) - .expect("unreachable"); - v.into_boxed_slice() - }; - - Ok(Signature { - prepared_statement_name, + let mut sig = Signature { + prepared_statement_name: Box::default(), name: name.into_boxed_slice(), fields: fields.into_boxed_slice(), - }) + }; + if !unnamed { + sig.set_prepared_statement_name(prepared_statement_id); + } + Ok(sig) } } diff --git a/test/js/sql/postgres-prepared-statement-invalidation.test.ts b/test/js/sql/postgres-prepared-statement-invalidation.test.ts new file mode 100644 index 000000000000..d7013d1b8077 --- /dev/null +++ b/test/js/sql/postgres-prepared-statement-invalidation.test.ts @@ -0,0 +1,395 @@ +// A named prepared statement that the server invalidates (SQLSTATE 26000 after +// DEALLOCATE/DISCARD, or 0A000 "cached plan must not change result type" after +// a schema change) used to stay Prepared in the per-connection statement cache, +// so every later execution of that query bound the dead server-side name and +// failed forever. The ErrorResponse handler now evicts the cached entry and, +// when the failing exchange is the only one in flight, transparently +// re-prepares under a fresh name and re-runs once. +import { SQL, randomUUIDv7 } from "bun"; +import { expect, test } from "bun:test"; +import { describeWithContainer } from "harness"; +import { + listeningServer, + pgAuthenticationOk, + pgBindComplete, + pgCommandComplete, + pgDataRow, + pgErrorResponse, + pgParseComplete, + pgReadFrontendMessages, + pgReadyForQuery, + pgRowDescription, +} from "./wire-frames"; + +describeWithContainer("postgres", { image: "postgres_plain" }, container => { + const connect = () => + new SQL({ + url: `postgres://bun_sql_test@${container.host}:${container.port}/bun_sql_test`, + max: 1, + idleTimeout: 30, + }); + + test("ALTER TABLE (0A000) is recovered by re-preparing instead of poisoning the connection", async () => { + await container.ready; + await using sql = connect(); + const tbl = "t_inv_" + randomUUIDv7("hex").replaceAll("-", ""); + try { + await sql`create table ${sql(tbl)}(a int, b int)`.simple(); + await sql`insert into ${sql(tbl)} values (1, 2)`.simple(); + const q = () => sql`select * from ${sql(tbl)}`; + expect(await q()).toEqual([{ a: 1, b: 2 }]); + + await sql`alter table ${sql(tbl)} add column c int default 3`.simple(); + // Before the fix every call below rejected with errno 0A000; now the + // stale plan is re-prepared under a fresh name and the new column is + // returned. + expect(await q()).toEqual([{ a: 1, b: 2, c: 3 }]); + expect(await q()).toEqual([{ a: 1, b: 2, c: 3 }]); + + // ALTER COLUMN TYPE: the postgres.js "Recreate prepared statements on + // RevalidateCachedQuery error" case (same 0A000, different DDL shape). + await sql`alter table ${sql(tbl)} alter column b type text using b::text`.simple(); + expect(await q()).toEqual([{ a: 1, b: "2", c: 3 }]); + } finally { + await sql`drop table if exists ${sql(tbl)}`.simple(); + } + }); + + test("DEALLOCATE/DISCARD (26000) is recovered by re-preparing instead of poisoning the connection", async () => { + await container.ready; + await using sql = connect(); + const tbl = "t_inv_" + randomUUIDv7("hex").replaceAll("-", ""); + try { + await sql`create table ${sql(tbl)}(a int)`.simple(); + await sql`insert into ${sql(tbl)} values (7)`.simple(); + // With a parameter so the two-phase Parse+Describe / Bind+Execute path + // is exercised as well. + const q = (n: number) => sql`select a from ${sql(tbl)} where a = ${n}`; + expect(await q(7)).toEqual([{ a: 7 }]); + + await sql`deallocate all`.simple(); + expect(await q(7)).toEqual([{ a: 7 }]); + + await sql`discard all`.simple(); + expect(await q(7)).toEqual([{ a: 7 }]); + expect(await q(7)).toEqual([{ a: 7 }]); + } finally { + await sql`drop table if exists ${sql(tbl)}`.simple(); + } + }); + + test("a pipelined batch over an invalidated statement recovers for later queries", async () => { + await container.ready; + await using sql = connect(); + const tbl = "t_inv_" + randomUUIDv7("hex").replaceAll("-", ""); + try { + await sql`create table ${sql(tbl)}(x int)`.simple(); + await sql`insert into ${sql(tbl)} values (1)`.simple(); + const p = () => sql`select * from ${sql(tbl)}`; + expect(await p()).toEqual([{ x: 1 }]); + + await sql`alter table ${sql(tbl)} add column y int default 9`.simple(); + // Two Bind+Execute pipelined against the stale plan. Both were already + // on the wire when the first ErrorResponse arrives, so at least the + // first is surfaced; the second may be transparently re-prepared. + const [r0, r1] = await Promise.allSettled([p(), p()]); + expect(r0.status === "rejected" ? (r0.reason as any).errno : r0.value).toEqual( + r0.status === "rejected" ? "0A000" : [{ x: 1, y: 9 }], + ); + expect(r1.status === "rejected" ? (r1.reason as any).errno : r1.value).toEqual( + r1.status === "rejected" ? "0A000" : [{ x: 1, y: 9 }], + ); + // The connection must not be poisoned: the next execution succeeds. + // Before the fix this rejected with errno 0A000 forever. + expect(await p()).toEqual([{ x: 1, y: 9 }]); + } finally { + await sql`drop table if exists ${sql(tbl)}`.simple(); + } + }); + + test("a pipelined pair of parameterised queries over a DISCARDed statement recovers for later queries", async () => { + await container.ready; + await using sql = connect(); + const q = (n: number) => sql`select ${n}::int as v`; + expect(await q(1)).toEqual([{ v: 1 }]); + + await sql`discard all`.simple(); + // Both Binds name the discarded statement and are normally on the wire + // together, in which case the first is surfaced as 26000 and the second + // may be transparently re-prepared once the first has settled. Each must + // settle either way, and neither may hang. + const settled = await Promise.allSettled([q(2), q(3)]); + expect(settled.map(r => (r.status === "rejected" ? (r.reason as any).errno : r.value))).toEqual( + settled.map((r, i) => (r.status === "rejected" ? "26000" : [{ v: i + 2 }])), + ); + + // Before the fix this rejected with errno 26000 forever. + expect(await q(4)).toEqual([{ v: 4 }]); + }); + + test("a 0A000 raised by the query itself keeps the statement cached and is not retried", async () => { + await container.ready; + await using sql = connect(); + const fn = "fn_inv_" + randomUUIDv7("hex").replaceAll("-", ""); + try { + // This 0A000 comes from PL/pgSQL (routine exec_stmt_raise), not from the + // plan cache: the prepared statement is fine and must stay cached. + await sql` + create function ${sql(fn)}(int) returns int as $$ begin raise feature_not_supported; end $$ language plpgsql + `.simple(); + const call = (n: number) => sql`select ${sql(fn)}(${n})`.catch(e => e); + // The only prepared statement mentioning the function is the call above + // (create/drop run through the simple protocol and are never prepared). + const prepared = () => sql`select name from pg_prepared_statements where statement like ${"%" + fn + "%"}`; + + const first = await call(0); + expect(first.errno).toBe("0A000"); + expect(first.routine).not.toBe("RevalidateCachedQuery"); + + const before = await prepared(); + expect(before).toHaveLength(1); + const again = await Promise.all([call(1), call(2), call(3)]); + expect(again.map(e => e.errno)).toEqual(["0A000", "0A000", "0A000"]); + // Same server-side name as before: nothing was evicted or re-prepared. + expect(await prepared()).toEqual(before); + } finally { + await sql`drop function if exists ${sql(fn)}(int)`.simple(); + } + }); + + test("inside a transaction block the original 0A000 is surfaced (not masked by a retry)", async () => { + await container.ready; + await using sql = connect(); + const tbl = "t_inv_" + randomUUIDv7("hex").replaceAll("-", ""); + try { + await sql`create table ${sql(tbl)}(a int, b int)`.simple(); + await sql`insert into ${sql(tbl)} values (1, 2)`.simple(); + const q = () => sql`select * from ${sql(tbl)}`; + expect(await q()).toEqual([{ a: 1, b: 2 }]); + await sql`alter table ${sql(tbl)} add column c int default 3`.simple(); + + // Inside an open transaction block a re-Parse would be rejected with + // 25P02 (current transaction is aborted), so the retry is suppressed + // and the caller sees the real invalidation error. + await sql`BEGIN`.simple(); + const err = await q().catch(e => e); + await sql`ROLLBACK`.simple(); + expect((err as any)?.errno).toBe("0A000"); + + // The cache was still evicted, so the connection recovers after + // ROLLBACK. Before the fix this rejected with errno 0A000 forever. + expect(await q()).toEqual([{ a: 1, b: 2, c: 3 }]); + } finally { + await sql`drop table if exists ${sql(tbl)}`.simple(); + } + }); +}); + +// Wire-level counterpart: runs without a container. The scripted server forgets +// every prepared statement after the first successful execution, so the next +// Bind answers 26000. The client must evict its cache entry and Parse a fresh +// name; the test asserts the second Parse name differs from the first and that +// the query resolves. +test("postgres: a 26000 on Bind evicts the cached statement and re-prepares under a new name", async () => { + const parses: string[] = []; + const { port, server } = await listeningServer(socket => { + let sawStartup = false; + let pending = Buffer.alloc(0); + const known = new Set(); + let boundName: string | null = null; + const rowDesc = pgRowDescription([{ name: "v", typeOid: 25 }]); + socket.on("error", () => {}); + socket.on("data", chunk => { + pending = Buffer.concat([pending, chunk]); + if (!sawStartup) { + if (pending.length < 4) return; + const len = pending.readInt32BE(0); + if (pending.length < len) return; + pending = pending.subarray(len); + sawStartup = true; + socket.write(Buffer.concat([pgAuthenticationOk(), pgReadyForQuery()])); + } + const out: Buffer[] = []; + pending = pgReadFrontendMessages(pending, (type, body) => { + switch (type) { + case 0x50 /* 'P' Parse */: { + const name = body.subarray(0, body.indexOf(0)).toString("utf-8"); + parses.push(name); + known.add(name); + out.push(pgParseComplete()); + break; + } + case 0x44 /* 'D' Describe */: + out.push(rowDesc); + break; + case 0x42 /* 'B' Bind */: { + const afterPortal = body.indexOf(0) + 1; + const name = body.subarray(afterPortal, body.indexOf(0, afterPortal)).toString("utf-8"); + if (known.has(name)) { + boundName = name; + out.push(pgBindComplete()); + } else { + boundName = null; + out.push(pgErrorResponse({ S: "ERROR", C: "26000", M: `prepared statement "${name}" does not exist` })); + } + break; + } + case 0x45 /* 'E' Execute */: + if (boundName !== null) { + out.push(pgDataRow([Buffer.from("ok")]), pgCommandComplete("SELECT 1")); + } + break; + case 0x53 /* 'S' Sync */: + if (boundName !== null) { + // Forget every statement after one successful exchange, as if + // the backend ran DEALLOCATE ALL. + known.clear(); + boundName = null; + } + out.push(pgReadyForQuery()); + break; + case 0x48 /* 'H' Flush */: + case 0x58 /* 'X' Terminate */: + break; + default: + break; + } + }); + if (out.length) socket.write(Buffer.concat(out)); + }); + }); + + try { + await using sql = new SQL({ url: `postgres://u@127.0.0.1:${port}/db`, max: 1, idleTimeout: 5 }); + const q = () => sql`select v`; + // First run: Parse name #0, Bind, Execute → ok. Server then forgets it. + expect(await q()).toEqual([{ v: "ok" }]); + // Second run: cache hit, Bind name #0 → 26000. Client must evict + Parse a + // new name + re-run; before the fix this rejected with errno 26000. + expect(await q()).toEqual([{ v: "ok" }]); + // Third run: same again (cache was re-populated with the new name, which + // the server has now also forgotten). + expect(await q()).toEqual([{ v: "ok" }]); + + expect({ + parseCount: parses.length, + uniqueNames: new Set(parses).size, + }).toEqual({ + parseCount: 3, + uniqueNames: 3, + }); + } finally { + server.close(); + } +}); + +// The retry is capped at one attempt per query: a server that answers every +// Bind with 26000 must not loop forever. +test("postgres: a 26000 on the re-prepared Bind is surfaced instead of retried again", async () => { + let parses = 0; + const { port, server } = await listeningServer(socket => { + let sawStartup = false; + let pending = Buffer.alloc(0); + const rowDesc = pgRowDescription([{ name: "v", typeOid: 25 }]); + socket.on("error", () => {}); + socket.on("data", chunk => { + pending = Buffer.concat([pending, chunk]); + if (!sawStartup) { + if (pending.length < 4) return; + const len = pending.readInt32BE(0); + if (pending.length < len) return; + pending = pending.subarray(len); + sawStartup = true; + socket.write(Buffer.concat([pgAuthenticationOk(), pgReadyForQuery()])); + } + const out: Buffer[] = []; + pending = pgReadFrontendMessages(pending, (type, body) => { + if (type === 0x50 /* Parse */) { + parses++; + out.push(pgParseComplete()); + } else if (type === 0x44 /* Describe */) { + out.push(rowDesc); + } else if (type === 0x42 /* Bind */) { + const afterPortal = body.indexOf(0) + 1; + const name = body.subarray(afterPortal, body.indexOf(0, afterPortal)).toString("utf-8"); + out.push(pgErrorResponse({ S: "ERROR", C: "26000", M: `prepared statement "${name}" does not exist` })); + } else if (type === 0x53 /* Sync */) { + out.push(pgReadyForQuery()); + } + }); + if (out.length) socket.write(Buffer.concat(out)); + }); + }); + + try { + await using sql = new SQL({ url: `postgres://u@127.0.0.1:${port}/db`, max: 1, idleTimeout: 5 }); + const err = await sql`select v`.catch(e => e); + expect({ errno: (err as any)?.errno, parses }).toEqual({ errno: "26000", parses: 2 }); + } finally { + server.close(); + } +}); + +// 0A000 is the generic feature_not_supported class; only the plancache +// RevalidateCachedQuery case means the prepared statement is stale. An +// execute-time 0A000 from anything else must not trigger a silent re-execute. +test("postgres: a 0A000 without routine RevalidateCachedQuery is not retried", async () => { + let parses = 0; + let executes = 0; + const { port, server } = await listeningServer(socket => { + let sawStartup = false; + let pending = Buffer.alloc(0); + const rowDesc = pgRowDescription([{ name: "v", typeOid: 25 }]); + socket.on("error", () => {}); + socket.on("data", chunk => { + pending = Buffer.concat([pending, chunk]); + if (!sawStartup) { + if (pending.length < 4) return; + const len = pending.readInt32BE(0); + if (pending.length < len) return; + pending = pending.subarray(len); + sawStartup = true; + socket.write(Buffer.concat([pgAuthenticationOk(), pgReadyForQuery()])); + } + const out: Buffer[] = []; + pending = pgReadFrontendMessages(pending, type => { + if (type === 0x50 /* Parse */) { + parses++; + out.push(pgParseComplete()); + } else if (type === 0x44 /* Describe */) { + out.push(rowDesc); + } else if (type === 0x42 /* Bind */) { + out.push(pgBindComplete()); + } else if (type === 0x45 /* Execute */) { + executes++; + if (executes === 1) { + out.push(pgDataRow([Buffer.from("ok")]), pgCommandComplete("SELECT 1")); + } else { + out.push(pgErrorResponse({ S: "ERROR", C: "0A000", M: "feature not supported", R: "some_fdw_handler" })); + } + } else if (type === 0x53 /* Sync */) { + out.push(pgReadyForQuery()); + } + }); + if (out.length) socket.write(Buffer.concat(out)); + }); + }); + + try { + await using sql = new SQL({ url: `postgres://u@127.0.0.1:${port}/db`, max: 1, idleTimeout: 5 }); + expect(await sql`select v`).toEqual([{ v: "ok" }]); + const err = await sql`select v`.catch(e => e); + // Exactly one Parse and two Executes: the first run prepared and + // succeeded, the second hit the cache and was rejected at Execute. No + // silent re-prepare (which would have bumped parses to 2 and executes + // to 3). + expect({ errno: (err as any)?.errno, routine: (err as any)?.routine, parses, executes }).toEqual({ + errno: "0A000", + routine: "some_fdw_handler", + parses: 1, + executes: 2, + }); + } finally { + server.close(); + } +}); diff --git a/test/js/sql/sql.test.ts b/test/js/sql/sql.test.ts index 75ce11d3b130..e9154523ce6c 100644 --- a/test/js/sql/sql.test.ts +++ b/test/js/sql/sql.test.ts @@ -3145,18 +3145,8 @@ if (isDockerEnabled()) { // ] // }) - // t('Recreate prepared statements on RevalidateCachedQuery error', async() => { - // const select = () => sql`select name from test` - // await sql`create table test (name text)` - // await sql`insert into test values ('1')` - // await select() - // await sql`alter table test alter column name type int using name::integer` - // return [ - // 1, - // (await select())[0].name, - // await sql`drop table test` - // ] - // }) + // "Recreate prepared statements on RevalidateCachedQuery error" is covered + // by test/js/sql/postgres-prepared-statement-invalidation.test.ts. // t('Catches connection config errors', async() => { // const sql = postgres({ ...options, user: { toString: () => { throw new Error('wat') } }, database: 'prut' }) From fb3fd16d461aa8d80344b490bdd00819fc64396f Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 6 Sep 2026 19:19:14 +0000 Subject: [PATCH 02/12] sql(postgres): shorten the evict_statement doc comment --- src/sql_jsc/postgres/PostgresSQLConnection.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index 42e919952970..20c98b342e8d 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -1537,9 +1537,7 @@ impl PostgresSQLConnection { } } - /// Drop the cache entry for `stmt`'s signature if it still points at - /// `stmt` (re-entrant JS may already have replaced it). The caller's - /// request holds its own ref, so this never frees `stmt`. + /// Remove the cache entry for `stmt` unless re-entrant JS already replaced it. fn evict_statement(&self, stmt: &PostgresSQLStatement) { let stmt_ptr: *const PostgresSQLStatement = core::ptr::from_ref(stmt); self.statements.with_mut(|m| { From c261ec4d99b73c7ab5c82c9848586fb2221f27fd Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 26 Sep 2026 22:50:46 +0000 Subject: [PATCH 03/12] sql(postgres): re-prepare only for an error that answers the Bind An invalidated statement is reported in answer to Bind. After BindComplete, SQLSTATE 26000 or 0A000 comes from the query itself, and rows of the request can have arrived. The retry kept those rows, so the query resolved with the rows of both attempts. --- src/sql_jsc/postgres/PostgresSQLConnection.rs | 6 +- ...es-prepared-statement-invalidation.test.ts | 112 +++++++++++++++++- 2 files changed, 116 insertions(+), 2 deletions(-) diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index 69afcc461720..27bb89ebb5d8 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -3001,10 +3001,14 @@ impl PostgresSQLConnection { self.evict_statement(stmt); } else if stmt.status == StatementStatus::Prepared && invalidates + && request.status.get() == QueryStatus::Binding && !stmt.signature.prepared_statement_name.is_empty() { // Server-side named statement gone or stale: evict so - // later queries with this signature re-prepare. + // later queries with this signature re-prepare. The + // server reports that in answer to Bind; after + // BindComplete the same SQLSTATE comes from the query + // itself, and rows of this request may have arrived. self.evict_statement(stmt); // Retry only when no other Bind/Execute responses are // already on the wire and the session is idle (inside a diff --git a/test/js/sql/postgres-prepared-statement-invalidation.test.ts b/test/js/sql/postgres-prepared-statement-invalidation.test.ts index d7013d1b8077..b01ab5f8c604 100644 --- a/test/js/sql/postgres-prepared-statement-invalidation.test.ts +++ b/test/js/sql/postgres-prepared-statement-invalidation.test.ts @@ -4,7 +4,8 @@ // so every later execution of that query bound the dead server-side name and // failed forever. The ErrorResponse handler now evicts the cached entry and, // when the failing exchange is the only one in flight, transparently -// re-prepares under a fresh name and re-runs once. +// re-prepares under a fresh name and re-runs once. Only an error that answers +// the Bind counts: after BindComplete the same SQLSTATE comes from the query. import { SQL, randomUUIDv7 } from "bun"; import { expect, test } from "bun:test"; import { describeWithContainer } from "harness"; @@ -157,6 +158,42 @@ describeWithContainer("postgres", { image: "postgres_plain" }, container => { } }); + test("a 26000 raised by the query itself after rows were sent is surfaced and not retried", async () => { + await container.ready; + await using sql = connect(); + const id = randomUUIDv7("hex").replaceAll("-", ""); + const seq = "seq_inv_" + id; + const fn = "fn_inv_" + id; + try { + await sql.unsafe(`create sequence ${seq}`); + // Raises on row 3 of its first run only. nextval is not rolled back, so + // the sequence counts the runs that reached row 3. + await sql.unsafe(` + create function ${fn}(i int) returns int as $$ + begin + if i = 3 and nextval('${seq}') = 1 then + raise exception 'boom' using errcode = '26000'; + end if; + return i; + end $$ language plpgsql + `); + const settled = await sql`select ${sql(fn)}(i::int) as v from generate_series(1, ${5}) as i`.catch(e => e); + const [{ runs }] = await sql.unsafe( + `select (case when is_called then last_value else 0 end)::int as runs from ${seq}`, + ); + // A retry runs the function a second time and resolves with the rows of + // both runs: [1, 2, 1, 2, 3, 4, 5]. + expect({ errno: (settled as any)?.errno, routine: (settled as any)?.routine, runs }).toEqual({ + errno: "26000", + routine: "exec_stmt_raise", + runs: 1, + }); + } finally { + await sql.unsafe(`drop function if exists ${fn}(int)`); + await sql.unsafe(`drop sequence if exists ${seq}`); + } + }); + test("inside a transaction block the original 0A000 is surfaced (not masked by a retry)", async () => { await container.ready; await using sql = connect(); @@ -393,3 +430,76 @@ test("postgres: a 0A000 without routine RevalidateCachedQuery is not retried", a server.close(); } }); + +// The position in the exchange decides, not the fields of the error. After +// BindComplete the server has found the statement and its plan, so a 26000 +// there comes from the query itself. Rows of the request can have arrived by +// then, and a retry would resolve with the rows of both attempts. +test("postgres: a 26000 after BindComplete is surfaced and the statement stays cached", async () => { + let parses = 0; + let executes = 0; + const { port, server } = await listeningServer(socket => { + let sawStartup = false; + let pending = Buffer.alloc(0); + const rowDesc = pgRowDescription([{ name: "v", typeOid: 25 }]); + socket.on("error", () => {}); + socket.on("data", chunk => { + pending = Buffer.concat([pending, chunk]); + if (!sawStartup) { + if (pending.length < 4) return; + const len = pending.readInt32BE(0); + if (pending.length < len) return; + pending = pending.subarray(len); + sawStartup = true; + socket.write(Buffer.concat([pgAuthenticationOk(), pgReadyForQuery()])); + } + const out: Buffer[] = []; + pending = pgReadFrontendMessages(pending, type => { + if (type === 0x50 /* Parse */) { + parses++; + out.push(pgParseComplete()); + } else if (type === 0x44 /* Describe */) { + out.push(rowDesc); + } else if (type === 0x42 /* Bind */) { + out.push(pgBindComplete()); + } else if (type === 0x45 /* Execute */) { + executes++; + if (executes === 2) { + out.push( + pgDataRow([Buffer.from("a")]), + pgDataRow([Buffer.from("b")]), + pgErrorResponse({ + S: "ERROR", + C: "26000", + M: 'prepared statement "other" does not exist', + R: "FetchPreparedStatement", + }), + ); + } else { + out.push(pgDataRow([Buffer.from("ok")]), pgCommandComplete("SELECT 1")); + } + } else if (type === 0x53 /* Sync */) { + out.push(pgReadyForQuery()); + } + }); + if (out.length) socket.write(Buffer.concat(out)); + }); + }); + + try { + await using sql = new SQL({ url: `postgres://u@127.0.0.1:${port}/db`, max: 1, idleTimeout: 5 }); + expect(await sql`select v`).toEqual([{ v: "ok" }]); + const err = await sql`select v`.catch(e => e); + const after = await sql`select v`; + // One Parse for three runs: the second run was not re-prepared, and the + // third one still found the statement in the cache. + expect({ errno: (err as any)?.errno, after, parses, executes }).toEqual({ + errno: "26000", + after: [{ v: "ok" }], + parses: 1, + executes: 3, + }); + } finally { + server.close(); + } +}); From 4db5c8defc47d2d95b961ea5a8bc1137b78570c0 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 26 Sep 2026 19:45:53 +0000 Subject: [PATCH 04/12] sql(postgres): re-run every pipelined query that hits a prepared-statement invalidation A Bind/Execute pipelined behind the one that first reports 26000 or 0A000 gets its own ErrorResponse. Move each such request behind the in-flight ones instead of rejecting it, and re-Parse once the pipeline drains. The statement keeps its fields and parameters across the reset so a sibling that still succeeds decodes under the old description. --- src/sql_jsc/postgres/PostgresSQLConnection.rs | 76 +++++++--- src/sql_jsc/postgres/PostgresSQLStatement.rs | 10 +- ...es-prepared-statement-invalidation.test.ts | 130 ++++++++++++++---- 3 files changed, 167 insertions(+), 49 deletions(-) diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index 27bb89ebb5d8..636085a2f694 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -1554,6 +1554,33 @@ impl PostgresSQLConnection { } } + /// Move the head request behind every request whose bytes are already on + /// the wire and behind earlier re-queued retries. Replies are attributed + /// to the FIFO head, so a retry must not sit in front of an in-flight + /// request. + fn requeue_for_retry(&self, request: &PostgresSQLQuery) { + self.requests.with_mut(|q| { + if !q.front().is_some_and(|f| core::ptr::eq(f.as_ptr(), request)) { + return; + } + let Some(head) = q.pop_front() else { return }; + let at = q + .iter() + .position(|r| { + r.status.get() == QueryStatus::Pending && !r.flags.get().reprepared + }) + .unwrap_or(q.len()); + debug_assert!( + q.iter().skip(at).all(|r| !matches!( + r.status.get(), + QueryStatus::Binding | QueryStatus::Running | QueryStatus::PartialResponse + )) && !self.flags.get().contains(ConnectionFlags::WAITING_TO_PREPARE), + "retry inserted ahead of a request that is on the wire" + ); + q.insert(at, head); + }); + } + /// Remove the cache entry for `stmt` unless re-entrant JS already replaced it. fn evict_statement(&self, stmt: &PostgresSQLStatement) { let stmt_ptr: *const PostgresSQLStatement = core::ptr::from_ref(stmt); @@ -2999,34 +3026,42 @@ impl PostgresSQLConnection { ); // The request still holds another ref; this cannot drop to 0. self.evict_statement(stmt); - } else if stmt.status == StatementStatus::Prepared - && invalidates + } else if invalidates + // Only an answer to Bind reports a missing or stale + // statement; after BindComplete the SQLSTATE comes from + // the query itself and rows may have arrived. && request.status.get() == QueryStatus::Binding && !stmt.signature.prepared_statement_name.is_empty() + && matches!( + stmt.status, + StatementStatus::Prepared | StatementStatus::Pending + ) { - // Server-side named statement gone or stale: evict so - // later queries with this signature re-prepare. The - // server reports that in answer to Bind; after - // BindComplete the same SQLSTATE comes from the query - // itself, and rows of this request may have arrived. - self.evict_statement(stmt); - // Retry only when no other Bind/Execute responses are - // already on the wire and the session is idle (inside a + // Prepared: the server-side name is gone or stale. + // Pending: a pipelined sibling's ErrorResponse already + // reset it under a fresh name; this Bind named the old one. + let already_reset = stmt.status == StatementStatus::Pending; + if !already_reset { + // Evict so later queries with this signature re-prepare. + self.evict_statement(stmt); + } + // Retry only when the session is idle (inside a // transaction the retry Parse would be rejected 25P02). if !request.flags.get().reprepared && self.tx_status.get() == protocol::TransactionStatusIndicator::I - && self.pipelined_requests.get() <= 1 && self.nonpipelinable_requests.get() == 0 { debug!("re-preparing invalidated statement (SQLSTATE {})", err); self.finish_request(&request); - let id = self.prepared_statement_id.get(); - self.prepared_statement_id.set(id + 1); - stmt.reset_for_reprepare(id); - if let Some(statement) = request.statement.get().as_ref() { - let _ = self.statements.with_mut(|m| { - m.put(&statement.signature.name, Some(statement.clone())) - }); + if !already_reset { + let id = self.prepared_statement_id.get(); + self.prepared_statement_id.set(id + 1); + stmt.reset_for_reprepare(id); + if let Some(statement) = request.statement.get().as_ref() { + let _ = self.statements.with_mut(|m| { + m.put(&statement.signature.name, Some(statement.clone())) + }); + } } request.status.set(QueryStatus::Pending); request.update_flags(|f| { @@ -3034,11 +3069,12 @@ impl PostgresSQLConnection { f.binary = false; }); self.note_request_pending(); + // Siblings still on the wire answer first; the + // re-Parse waits for the pipeline to drain. + self.requeue_for_retry(&request); self.update_ref(); return Ok(()); } - // Leave the statement Prepared so the last pipelined - // sibling's ErrorResponse can still re-prepare it. } } // If `err` was not moved into stmt above, it drops here automatically. diff --git a/src/sql_jsc/postgres/PostgresSQLStatement.rs b/src/sql_jsc/postgres/PostgresSQLStatement.rs index a8a614fb43bd..5d52bc62352e 100644 --- a/src/sql_jsc/postgres/PostgresSQLStatement.rs +++ b/src/sql_jsc/postgres/PostgresSQLStatement.rs @@ -68,15 +68,13 @@ pub use bun_sql::shared::statement_status::Status; impl PostgresSQLStatement { /// Reset to pre-Parse state under a fresh server-side name so `advance()` - /// re-Parses after a 26000/0A000 invalidation. + /// re-Parses after a 26000/0A000 invalidation. The statement stays cached + /// as `Pending` while Binds under the previous name may still be on the + /// wire. `fields` and `parameters` stay: those siblings decode under them, + /// and the re-Parse's Describe replaces them. pub(crate) fn reset_for_reprepare(&mut self, prepared_statement_id: u64) { self.status = Status::Pending; self.error_response = None; - self.fields = Vec::new(); - self.parameters = Box::default(); - self.cached_structure = PostgresCachedStructure::default(); - self.needs_duplicate_check = true; - self.fields_flags = DataCellFlags::default(); self.signature .set_prepared_statement_name(prepared_statement_id); } diff --git a/test/js/sql/postgres-prepared-statement-invalidation.test.ts b/test/js/sql/postgres-prepared-statement-invalidation.test.ts index b01ab5f8c604..0733b171fb13 100644 --- a/test/js/sql/postgres-prepared-statement-invalidation.test.ts +++ b/test/js/sql/postgres-prepared-statement-invalidation.test.ts @@ -2,10 +2,12 @@ // DEALLOCATE/DISCARD, or 0A000 "cached plan must not change result type" after // a schema change) used to stay Prepared in the per-connection statement cache, // so every later execution of that query bound the dead server-side name and -// failed forever. The ErrorResponse handler now evicts the cached entry and, -// when the failing exchange is the only one in flight, transparently -// re-prepares under a fresh name and re-runs once. Only an error that answers -// the Bind counts: after BindComplete the same SQLSTATE comes from the query. +// failed forever. The ErrorResponse handler now evicts the cached entry, +// re-prepares under a fresh name and re-runs each affected query once. A +// pipelined sibling still on the wire gets its own ErrorResponse and is +// re-queued behind the others, so a whole burst recovers. Only an error that +// answers the Bind counts: after BindComplete the same SQLSTATE comes from the +// query. import { SQL, randomUUIDv7 } from "bun"; import { expect, test } from "bun:test"; import { describeWithContainer } from "harness"; @@ -13,9 +15,12 @@ import { listeningServer, pgAuthenticationOk, pgBindComplete, + pgBindParameters, pgCommandComplete, pgDataRow, pgErrorResponse, + pgMockServer, + pgParameterDescription, pgParseComplete, pgReadFrontendMessages, pgReadyForQuery, @@ -90,17 +95,10 @@ describeWithContainer("postgres", { image: "postgres_plain" }, container => { expect(await p()).toEqual([{ x: 1 }]); await sql`alter table ${sql(tbl)} add column y int default 9`.simple(); - // Two Bind+Execute pipelined against the stale plan. Both were already - // on the wire when the first ErrorResponse arrives, so at least the - // first is surfaced; the second may be transparently re-prepared. - const [r0, r1] = await Promise.allSettled([p(), p()]); - expect(r0.status === "rejected" ? (r0.reason as any).errno : r0.value).toEqual( - r0.status === "rejected" ? "0A000" : [{ x: 1, y: 9 }], - ); - expect(r1.status === "rejected" ? (r1.reason as any).errno : r1.value).toEqual( - r1.status === "rejected" ? "0A000" : [{ x: 1, y: 9 }], - ); - // The connection must not be poisoned: the next execution succeeds. + // Two Bind+Execute pipelined against the stale plan. Both are already + // on the wire when the first ErrorResponse arrives; each is re-queued + // behind the other and re-run once under the fresh name. + expect(await Promise.all([p(), p()])).toEqual([[{ x: 1, y: 9 }], [{ x: 1, y: 9 }]]); // Before the fix this rejected with errno 0A000 forever. expect(await p()).toEqual([{ x: 1, y: 9 }]); } finally { @@ -115,19 +113,39 @@ describeWithContainer("postgres", { image: "postgres_plain" }, container => { expect(await q(1)).toEqual([{ v: 1 }]); await sql`discard all`.simple(); - // Both Binds name the discarded statement and are normally on the wire - // together, in which case the first is surfaced as 26000 and the second - // may be transparently re-prepared once the first has settled. Each must - // settle either way, and neither may hang. - const settled = await Promise.allSettled([q(2), q(3)]); - expect(settled.map(r => (r.status === "rejected" ? (r.reason as any).errno : r.value))).toEqual( - settled.map((r, i) => (r.status === "rejected" ? "26000" : [{ v: i + 2 }])), - ); + // Both Binds name the discarded statement and are on the wire together. + // Each gets its own 26000, and each is re-run once under the fresh name, + // in order. + expect(await Promise.all([q(2), q(3)])).toEqual([[{ v: 2 }], [{ v: 3 }]]); // Before the fix this rejected with errno 26000 forever. expect(await q(4)).toEqual([{ v: 4 }]); }); + test("a concurrent burst over an invalidated statement re-runs every query", async () => { + await container.ready; + await using sql = connect(); + const tbl = "t_inv_" + randomUUIDv7("hex").replaceAll("-", ""); + try { + await sql`create table ${sql(tbl)}(id int primary key, a int)`.simple(); + await sql`insert into ${sql(tbl)} values (1, 1)`.simple(); + const select = (n: number) => sql`select * from ${sql(tbl)} where id = ${n}`; + await Promise.all(Array.from({ length: 20 }, () => select(1))); + + await sql`alter table ${sql(tbl)} add column b int`.simple(); + // Twenty Bind+Execute for the stale plan are on the wire when the first + // 0A000 arrives. Every one of them is re-run under the fresh name, so + // a migration that lands under load does not fail a burst of requests. + // With the retry limited to the last request in flight, 19 of these + // rejected with errno 0A000. + const burst = await Promise.all(Array.from({ length: 20 }, () => select(1))); + expect(burst).toEqual(Array.from({ length: 20 }, () => [{ id: 1, a: 1, b: null }])); + expect(await select(1)).toEqual([{ id: 1, a: 1, b: null }]); + } finally { + await sql`drop table if exists ${sql(tbl)}`.simple(); + } + }); + test("a 0A000 raised by the query itself keeps the statement cached and is not retried", async () => { await container.ready; await using sql = connect(); @@ -320,6 +338,72 @@ test("postgres: a 26000 on Bind evicts the cached statement and re-prepares unde } }); +// Pipelined siblings: five Binds for the stale name are on the wire when the +// first 26000 arrives, and a sixth query with a new statement text is queued +// behind them. Every sibling is answered 26000 in turn, the client Parses the +// fresh name once, re-runs all five in their original order, and only then +// Parses the sixth. +test("postgres: every pipelined Bind that hits 26000 is re-run once under one fresh name", async () => { + const parses: string[] = []; + let bindErrors = 0; + const known = new Set(); + let forgetAfterNextSync = true; + let bound: Buffer | null = null; + const mock = await pgMockServer((type, body) => { + switch (type) { + case "P": { + const name = body.subarray(0, body.indexOf(0)).toString("utf-8"); + parses.push(name); + known.add(name); + return pgParseComplete(); + } + case "D": + return [pgParameterDescription([25 /* text */]), pgRowDescription([{ name: "v", typeOid: 25 }])]; + case "B": { + const afterPortal = body.indexOf(0) + 1; + const name = body.subarray(afterPortal, body.indexOf(0, afterPortal)).toString("utf-8"); + if (!known.has(name)) { + bindErrors++; + bound = null; + return pgErrorResponse({ S: "ERROR", C: "26000", M: `prepared statement "${name}" does not exist` }); + } + bound = pgBindParameters(body)[0]!; + return pgBindComplete(); + } + case "E": + return bound === null ? undefined : [pgDataRow([bound]), pgCommandComplete("SELECT 1")]; + case "S": + if (bound !== null && forgetAfterNextSync) { + // As if the backend ran DEALLOCATE ALL after the warm-up. + known.clear(); + forgetAfterNextSync = false; + } + bound = null; + return pgReadyForQuery(); + } + }); + + try { + await using sql = new SQL({ url: `postgres://u@127.0.0.1:${mock.port}/db`, max: 1, idleTimeout: 5 }); + const echo = (text: string) => sql`select ${text} as v`; + const other = (text: string) => sql`select ${text}::text as v`; + expect(await echo("0")).toEqual([{ v: "0" }]); + + // Five Bind+Execute pipelined against the forgotten name, then a statement + // the server has never seen (its Parse waits for the pipeline to drain). + const results = await Promise.all([echo("1"), echo("2"), echo("3"), echo("4"), echo("5"), other("6")]); + expect({ results, bindErrors, parses: parses.length, uniqueNames: new Set(parses).size }).toEqual({ + results: [[{ v: "1" }], [{ v: "2" }], [{ v: "3" }], [{ v: "4" }], [{ v: "5" }], [{ v: "6" }]], + bindErrors: 5, + // warm-up, the one re-Parse, then `other` + parses: 3, + uniqueNames: 3, + }); + } finally { + mock.server.close(); + } +}); + // The retry is capped at one attempt per query: a server that answers every // Bind with 26000 must not loop forever. test("postgres: a 26000 on the re-prepared Bind is surfaced instead of retried again", async () => { From 45503600e7c15bcb61ba2009570099c64ec7a3f1 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Sat, 26 Sep 2026 23:47:57 +0000 Subject: [PATCH 05/12] [autofix.ci] apply automated fixes --- src/sql_jsc/postgres/PostgresSQLConnection.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index 636085a2f694..4bc0f5e08b98 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -1560,21 +1560,25 @@ impl PostgresSQLConnection { /// request. fn requeue_for_retry(&self, request: &PostgresSQLQuery) { self.requests.with_mut(|q| { - if !q.front().is_some_and(|f| core::ptr::eq(f.as_ptr(), request)) { + if !q + .front() + .is_some_and(|f| core::ptr::eq(f.as_ptr(), request)) + { return; } let Some(head) = q.pop_front() else { return }; let at = q .iter() - .position(|r| { - r.status.get() == QueryStatus::Pending && !r.flags.get().reprepared - }) + .position(|r| r.status.get() == QueryStatus::Pending && !r.flags.get().reprepared) .unwrap_or(q.len()); debug_assert!( q.iter().skip(at).all(|r| !matches!( r.status.get(), QueryStatus::Binding | QueryStatus::Running | QueryStatus::PartialResponse - )) && !self.flags.get().contains(ConnectionFlags::WAITING_TO_PREPARE), + )) && !self + .flags + .get() + .contains(ConnectionFlags::WAITING_TO_PREPARE), "retry inserted ahead of a request that is on the wire" ); q.insert(at, head); From 92b5cb28ae3af6d359150ce0588139c6d672e025 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 26 Sep 2026 23:50:35 +0000 Subject: [PATCH 06/12] sql(postgres): shorten the re-prepare comments --- src/sql_jsc/postgres/PostgresSQLConnection.rs | 20 ++++++------------- src/sql_jsc/postgres/PostgresSQLStatement.rs | 7 ++----- 2 files changed, 8 insertions(+), 19 deletions(-) diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index 4bc0f5e08b98..ee6040c70ac8 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -1554,10 +1554,8 @@ impl PostgresSQLConnection { } } - /// Move the head request behind every request whose bytes are already on - /// the wire and behind earlier re-queued retries. Replies are attributed - /// to the FIFO head, so a retry must not sit in front of an in-flight - /// request. + /// Move the head request behind every request already on the wire and + /// behind earlier re-queued retries. Replies are attributed to the head. fn requeue_for_retry(&self, request: &PostgresSQLQuery) { self.requests.with_mut(|q| { if !q @@ -3031,9 +3029,7 @@ impl PostgresSQLConnection { // The request still holds another ref; this cannot drop to 0. self.evict_statement(stmt); } else if invalidates - // Only an answer to Bind reports a missing or stale - // statement; after BindComplete the SQLSTATE comes from - // the query itself and rows may have arrived. + // After BindComplete the same SQLSTATE comes from the query. && request.status.get() == QueryStatus::Binding && !stmt.signature.prepared_statement_name.is_empty() && matches!( @@ -3041,16 +3037,13 @@ impl PostgresSQLConnection { StatementStatus::Prepared | StatementStatus::Pending ) { - // Prepared: the server-side name is gone or stale. - // Pending: a pipelined sibling's ErrorResponse already - // reset it under a fresh name; this Bind named the old one. + // Pending: a pipelined sibling already reset it under a fresh name. let already_reset = stmt.status == StatementStatus::Pending; if !already_reset { // Evict so later queries with this signature re-prepare. self.evict_statement(stmt); } - // Retry only when the session is idle (inside a - // transaction the retry Parse would be rejected 25P02). + // Inside a transaction block the re-Parse would get 25P02. if !request.flags.get().reprepared && self.tx_status.get() == protocol::TransactionStatusIndicator::I && self.nonpipelinable_requests.get() == 0 @@ -3073,8 +3066,7 @@ impl PostgresSQLConnection { f.binary = false; }); self.note_request_pending(); - // Siblings still on the wire answer first; the - // re-Parse waits for the pipeline to drain. + // The re-Parse waits for the siblings still on the wire. self.requeue_for_retry(&request); self.update_ref(); return Ok(()); diff --git a/src/sql_jsc/postgres/PostgresSQLStatement.rs b/src/sql_jsc/postgres/PostgresSQLStatement.rs index 5d52bc62352e..7b31e1760dd8 100644 --- a/src/sql_jsc/postgres/PostgresSQLStatement.rs +++ b/src/sql_jsc/postgres/PostgresSQLStatement.rs @@ -67,11 +67,8 @@ impl Error { pub use bun_sql::shared::statement_status::Status; impl PostgresSQLStatement { - /// Reset to pre-Parse state under a fresh server-side name so `advance()` - /// re-Parses after a 26000/0A000 invalidation. The statement stays cached - /// as `Pending` while Binds under the previous name may still be on the - /// wire. `fields` and `parameters` stay: those siblings decode under them, - /// and the re-Parse's Describe replaces them. + /// Reset to `Pending` under a fresh name so `advance()` re-Parses after 26000/0A000. + /// `fields` and `parameters` stay for Binds still on the wire under the old name. pub(crate) fn reset_for_reprepare(&mut self, prepared_statement_id: u64) { self.status = Status::Pending; self.error_response = None; From 02d5348aa18982732c33860e95ddaf553dc9c03e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 27 Sep 2026 02:08:31 +0000 Subject: [PATCH 07/12] sql(postgres): do not re-run a retried query inside a transaction block opened after it The idle check runs when the invalidation error arrives. The retry is written only after the requests ahead of it answer. If one of those opened a transaction block, surface the stored error instead of running the query inside a block it was issued before. --- src/sql_jsc/postgres/PostgresSQLConnection.rs | 20 +++++ src/sql_jsc/postgres/PostgresSQLQuery.rs | 4 + ...es-prepared-statement-invalidation.test.ts | 81 +++++++++++++++++++ 3 files changed, 105 insertions(+) diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index ee6040c70ac8..e37c765e0148 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -1944,6 +1944,25 @@ impl PostgresSQLConnection { // Parse written but not Bind / statement still Parsing) undo // this via note_request_pending() before returning/continuing. self.note_request_written(); + if req.flags.get().reprepared + && self.tx_status.get() != protocol::TransactionStatusIndicator::I + && let Some(err) = req.retry_error.take() + { + // A request on the wire ahead of the retry opened a + // transaction block. Surface the original error instead. + let ev = crate::postgres::protocol::error_response_jsc::to_js( + &err, + self.global(), + ); + req.on_js_error(ev, self.global()); + if offset == 0 { + self.discard_request(&req); + } else { + req.status.set(QueryStatus::Fail); + offset += 1; + } + continue; + } if req.flags.get().simple { if self.pipelined_requests.get() > 0 || !self @@ -3066,6 +3085,7 @@ impl PostgresSQLConnection { f.binary = false; }); self.note_request_pending(); + request.retry_error.set(Some(err)); // The re-Parse waits for the siblings still on the wire. self.requeue_for_retry(&request); self.update_ref(); diff --git a/src/sql_jsc/postgres/PostgresSQLQuery.rs b/src/sql_jsc/postgres/PostgresSQLQuery.rs index a3f88bc4faba..0d6772571cf3 100644 --- a/src/sql_jsc/postgres/PostgresSQLQuery.rs +++ b/src/sql_jsc/postgres/PostgresSQLQuery.rs @@ -53,6 +53,9 @@ pub struct PostgresSQLQuery { ref_count: Cell, pub(crate) flags: Cell, + /// The 26000/0A000 that triggered a re-prepare. Surfaced if the session + /// is no longer idle when the retry would be written. + pub(crate) retry_error: JsCell>, } impl Default for PostgresSQLQuery { @@ -64,6 +67,7 @@ impl Default for PostgresSQLQuery { status: Cell::new(Status::Pending), ref_count: Cell::new(1), flags: Cell::new(Flags::default()), + retry_error: JsCell::new(None), } } } diff --git a/test/js/sql/postgres-prepared-statement-invalidation.test.ts b/test/js/sql/postgres-prepared-statement-invalidation.test.ts index 0733b171fb13..98a0a3728df1 100644 --- a/test/js/sql/postgres-prepared-statement-invalidation.test.ts +++ b/test/js/sql/postgres-prepared-statement-invalidation.test.ts @@ -404,6 +404,87 @@ test("postgres: every pipelined Bind that hits 26000 is re-run once under one fr } }); +// The idle check runs when the error arrives, but the retry is written only +// after the requests ahead of it answer. If one of those is a BEGIN, the +// session is in a transaction block by then. The retry must not run inside a +// block the query was issued before: it surfaces the original error instead. +test("postgres: a retry queued behind a pipelined BEGIN surfaces the 26000 instead of running in the block", async () => { + const parses: string[] = []; + const queries = new Map(); // statement name -> query text + const known = new Set(); + let bound: { name: string; param: Buffer | null } | null = null; + let inBlock = false; + const mock = await pgMockServer((type, body) => { + switch (type) { + case "P": { + const name = body.subarray(0, body.indexOf(0)).toString("utf-8"); + const after = body.indexOf(0) + 1; + const query = body.subarray(after, body.indexOf(0, after)).toString("utf-8"); + parses.push(name); + queries.set(name, query); + known.add(name); + return pgParseComplete(); + } + case "D": { + const name = body.subarray(1, body.indexOf(0, 1)).toString("utf-8"); + const params = queries.get(name)!.includes("$1") ? [25 /* text */] : []; + return [pgParameterDescription(params), pgRowDescription([{ name: "v", typeOid: 25 }])]; + } + case "B": { + const afterPortal = body.indexOf(0) + 1; + const name = body.subarray(afterPortal, body.indexOf(0, afterPortal)).toString("utf-8"); + if (!known.has(name)) { + bound = null; + return pgErrorResponse({ S: "ERROR", C: "26000", M: `prepared statement "${name}" does not exist` }); + } + bound = { name, param: pgBindParameters(body)[0] ?? null }; + return pgBindComplete(); + } + case "E": { + if (bound === null) return; + const query = queries.get(bound.name)!; + if (query === "BEGIN") { + inBlock = true; + return pgCommandComplete("BEGIN"); + } + if (query === "COMMIT") { + inBlock = false; + return pgCommandComplete("COMMIT"); + } + return [pgDataRow([bound.param!]), pgCommandComplete("SELECT 1")]; + } + case "S": + bound = null; + return pgReadyForQuery(inBlock ? "T" : "I"); + } + }); + + try { + await using sql = new SQL({ url: `postgres://u@127.0.0.1:${mock.port}/db`, max: 1, idleTimeout: 5 }); + const echo = (text: string) => sql`select ${text} as v`; + expect(await echo("0")).toEqual([{ v: "0" }]); + await sql`BEGIN`; + await sql`COMMIT`; + // The server forgets the select statement only. BEGIN stays prepared, so + // the next BEGIN is a cache hit and pipelines behind the stale select. + for (const [name, query] of queries) if (query !== "BEGIN" && query !== "COMMIT") known.delete(name); + + const [stale, begin] = await Promise.allSettled([echo("1"), sql`BEGIN`]); + await sql`COMMIT`; + // With the session idle again the next run re-prepares as usual. + const after = await echo("2"); + expect({ + stale: stale.status === "rejected" ? (stale.reason as any).errno : stale.value, + begin: begin.status, + after, + // warm-up select, BEGIN, COMMIT, then only the re-Parse for echo("2") + parses: parses.length, + }).toEqual({ stale: "26000", begin: "fulfilled", after: [{ v: "2" }], parses: 4 }); + } finally { + mock.server.close(); + } +}); + // The retry is capped at one attempt per query: a server that answers every // Bind with 26000 must not loop forever. test("postgres: a 26000 on the re-prepared Bind is surfaced instead of retried again", async () => { From 2134b4d03ae734ec98d2f2edd0f17ccf39027a65 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 27 Sep 2026 02:20:41 +0000 Subject: [PATCH 08/12] sql(postgres): shorten two retry comments --- src/sql_jsc/postgres/PostgresSQLConnection.rs | 3 +-- src/sql_jsc/postgres/PostgresSQLQuery.rs | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index e37c765e0148..9e928127e5c8 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -1948,8 +1948,7 @@ impl PostgresSQLConnection { && self.tx_status.get() != protocol::TransactionStatusIndicator::I && let Some(err) = req.retry_error.take() { - // A request on the wire ahead of the retry opened a - // transaction block. Surface the original error instead. + // A request ahead of the retry opened a transaction block. let ev = crate::postgres::protocol::error_response_jsc::to_js( &err, self.global(), diff --git a/src/sql_jsc/postgres/PostgresSQLQuery.rs b/src/sql_jsc/postgres/PostgresSQLQuery.rs index 0d6772571cf3..5906a1ee1196 100644 --- a/src/sql_jsc/postgres/PostgresSQLQuery.rs +++ b/src/sql_jsc/postgres/PostgresSQLQuery.rs @@ -53,8 +53,7 @@ pub struct PostgresSQLQuery { ref_count: Cell, pub(crate) flags: Cell, - /// The 26000/0A000 that triggered a re-prepare. Surfaced if the session - /// is no longer idle when the retry would be written. + /// The 26000/0A000 behind a re-prepare, surfaced if the session leaves idle first. pub(crate) retry_error: JsCell>, } From f9a42a60fbbc71baf8478bcb8ca3647f68b56450 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 27 Sep 2026 02:52:53 +0000 Subject: [PATCH 09/12] sql(postgres): mark the connection not ready on ErrorResponse until its ReadyForQuery An earlier pipelined sibling's ReadyForQuery leaves IS_READY_FOR_QUERY set while a later sibling's error batch is still open. With the failed request's pipelined count released, a query enqueued before that batch's ReadyForQuery made advance() write a Parse early. The ReadyForQuery then pipelined the new query ahead of the retry's Bind and the replies crossed. --- src/sql_jsc/postgres/PostgresSQLConnection.rs | 2 + ...es-prepared-statement-invalidation.test.ts | 75 +++++++++++++++++++ 2 files changed, 77 insertions(+) diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index 9e928127e5c8..7d16e586beee 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -3033,6 +3033,8 @@ impl PostgresSQLConnection { debug!("ErrorResponse: {}", err); return Err(AnyPostgresError::ExpectedRequest); }; + // The ReadyForQuery that ends this batch is still to come. + self.update_flags(|f| f.remove(ConnectionFlags::IS_READY_FOR_QUERY)); let invalidates = err.invalidates_prepared_statement(); // Convert to JS while we still own `err` — materialize the JS value once and route through // `on_js_error` to avoid double-ownership of the non-Clone ErrorResponse. diff --git a/test/js/sql/postgres-prepared-statement-invalidation.test.ts b/test/js/sql/postgres-prepared-statement-invalidation.test.ts index 98a0a3728df1..5785d75f3d31 100644 --- a/test/js/sql/postgres-prepared-statement-invalidation.test.ts +++ b/test/js/sql/postgres-prepared-statement-invalidation.test.ts @@ -19,6 +19,7 @@ import { pgCommandComplete, pgDataRow, pgErrorResponse, + pgHold, pgMockServer, pgParameterDescription, pgParseComplete, @@ -404,6 +405,80 @@ test("postgres: every pipelined Bind that hits 26000 is re-run once under one fr } }); +// The server flushes an ErrorResponse before the ReadyForQuery that ends the +// batch, so the two can arrive in separate reads. An earlier sibling's +// ReadyForQuery has already marked the connection ready. A query enqueued in +// that window must not make the client write the re-Parse before the error +// batch's ReadyForQuery: the later ReadyForQuery would then pipeline the new +// query ahead of the retry's Bind and hand each the other's rows. +test("postgres: a query enqueued between a sibling's ErrorResponse and its ReadyForQuery keeps its own rows", async () => { + const parses: string[] = []; + const queries = new Map(); + const known = new Set(); + let bound: Buffer | null = null; + let bindFailed = false; + let holdOnce = true; + const mock = await pgMockServer((type, body) => { + switch (type) { + case "P": { + const name = body.subarray(0, body.indexOf(0)).toString("utf-8"); + const after = body.indexOf(0) + 1; + queries.set(name, body.subarray(after, body.indexOf(0, after)).toString("utf-8")); + parses.push(name); + known.add(name); + return pgParseComplete(); + } + case "D": + return [pgParameterDescription([25 /* text */]), pgRowDescription([{ name: "v", typeOid: 25 }])]; + case "B": { + const afterPortal = body.indexOf(0) + 1; + const name = body.subarray(afterPortal, body.indexOf(0, afterPortal)).toString("utf-8"); + if (!known.has(name)) { + bound = null; + bindFailed = true; + return pgErrorResponse({ S: "ERROR", C: "26000", M: `prepared statement "${name}" does not exist` }); + } + bound = pgBindParameters(body)[0]!; + return pgBindComplete(); + } + case "E": + return bound === null ? undefined : [pgDataRow([bound]), pgCommandComplete("SELECT 1")]; + case "S": { + bound = null; + const hold = bindFailed && holdOnce; + bindFailed = false; + if (hold) { + holdOnce = false; + return [pgHold, pgReadyForQuery()]; + } + return pgReadyForQuery(); + } + } + }); + + try { + await using sql = new SQL({ url: `postgres://u@127.0.0.1:${mock.port}/db`, max: 1, idleTimeout: 5 }); + const echo = (text: string) => sql`select ${text} as v`; + const other = (text: string) => sql`select ${text}::text as v`; + expect(await echo("0")).toEqual([{ v: "0" }]); + expect(await other("a")).toEqual([{ v: "a" }]); + for (const [name, query] of queries) if (!query.includes("::text")) known.delete(name); + + // execute() sends at once, so these two are pipelined: `other` succeeds, + // `echo` gets 26000 and its ReadyForQuery is held back. + const s0 = other("b").execute(); + const s1 = echo("1").execute(); + expect(await s0).toEqual([{ v: "b" }]); + // Enqueued while the error batch's ReadyForQuery is outstanding. + const s3 = other("x").execute(); + mock.release(); + expect(await Promise.all([s1, s3])).toEqual([[{ v: "1" }], [{ v: "x" }]]); + expect(parses.length).toBe(3); + } finally { + mock.server.close(); + } +}); + // The idle check runs when the error arrives, but the retry is written only // after the requests ahead of it answer. If one of those is a BEGIN, the // session is in a transaction block by then. The retry must not run inside a From aaa9eb6b27cc61894daa2cc4eb258bf182ea8454 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 27 Sep 2026 11:32:09 +0000 Subject: [PATCH 10/12] sql(postgres): give a re-prepare its own statement object A re-prepare reset the cached statement in place and kept its column descriptions for the requests still on the wire. A query issued between the ParseComplete and the RowDescription of the re-prepare was bound with those descriptions. The server sent a value in one format and the client read it in the other. The invalidated statement now stays as it is. The retry, and each queued request that is not on the wire, get a new statement under a new name. --- src/sql_jsc/postgres/PostgresSQLConnection.rs | 66 ++++++--- src/sql_jsc/postgres/PostgresSQLStatement.rs | 9 -- src/sql_jsc/postgres/Signature.rs | 11 ++ ...es-prepared-statement-invalidation.test.ts | 136 ++++++++++++++++++ test/js/sql/wire-frames.ts | 18 +++ 5 files changed, 211 insertions(+), 29 deletions(-) diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index 7d16e586beee..ad44c1c6bc85 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -1599,6 +1599,48 @@ impl PostgresSQLConnection { }); } + /// Give `request`, and each queued request that holds the same evicted statement + /// and is not on the wire, the statement that takes its place: the one a + /// pipelined sibling or a later query already cached, or a new one. The evicted + /// statement keeps the description the requests on the wire were bound with. + fn replace_statement(&self, request: &PostgresSQLQuery) { + let Some(invalidated) = request.statement.get().clone() else { + return; + }; + let name = &invalidated.signature.name[..]; + let cached = self + .statements + .get() + .get(name) + .and_then(|slot| slot.clone()); + let replacement = cached.unwrap_or_else(|| { + let id = self.prepared_statement_id.get(); + self.prepared_statement_id.set(id + 1); + let statement = { + let mut s = PostgresSQLStatement::default(); + s.signature = invalidated.signature.renamed(id); + RefPtr::new(s) + }; + let _ = self + .statements + .with_mut(|m| m.put(name, Some(statement.clone()))); + statement + }); + debug_assert!(!core::ptr::eq(replacement.as_ptr(), invalidated.as_ptr())); + for queued in self.requests.get().iter() { + if queued.status.get() == QueryStatus::Pending + && queued + .statement + .get() + .as_ref() + .is_some_and(|held| core::ptr::eq(held.as_ptr(), invalidated.as_ptr())) + { + queued.statement.set(Some(replacement.clone())); + } + } + request.statement.set(Some(replacement)); + } + pub(crate) fn has_query_running(&self) -> bool { !self .flags @@ -3051,18 +3093,11 @@ impl PostgresSQLConnection { } else if invalidates // After BindComplete the same SQLSTATE comes from the query. && request.status.get() == QueryStatus::Binding + && stmt.status == StatementStatus::Prepared && !stmt.signature.prepared_statement_name.is_empty() - && matches!( - stmt.status, - StatementStatus::Prepared | StatementStatus::Pending - ) { - // Pending: a pipelined sibling already reset it under a fresh name. - let already_reset = stmt.status == StatementStatus::Pending; - if !already_reset { - // Evict so later queries with this signature re-prepare. - self.evict_statement(stmt); - } + // Evict so later queries with this signature re-prepare. + self.evict_statement(stmt); // Inside a transaction block the re-Parse would get 25P02. if !request.flags.get().reprepared && self.tx_status.get() == protocol::TransactionStatusIndicator::I @@ -3070,16 +3105,7 @@ impl PostgresSQLConnection { { debug!("re-preparing invalidated statement (SQLSTATE {})", err); self.finish_request(&request); - if !already_reset { - let id = self.prepared_statement_id.get(); - self.prepared_statement_id.set(id + 1); - stmt.reset_for_reprepare(id); - if let Some(statement) = request.statement.get().as_ref() { - let _ = self.statements.with_mut(|m| { - m.put(&statement.signature.name, Some(statement.clone())) - }); - } - } + self.replace_statement(&request); request.status.set(QueryStatus::Pending); request.update_flags(|f| { f.reprepared = true; diff --git a/src/sql_jsc/postgres/PostgresSQLStatement.rs b/src/sql_jsc/postgres/PostgresSQLStatement.rs index 7b31e1760dd8..b2415624ec8e 100644 --- a/src/sql_jsc/postgres/PostgresSQLStatement.rs +++ b/src/sql_jsc/postgres/PostgresSQLStatement.rs @@ -67,15 +67,6 @@ impl Error { pub use bun_sql::shared::statement_status::Status; impl PostgresSQLStatement { - /// Reset to `Pending` under a fresh name so `advance()` re-Parses after 26000/0A000. - /// `fields` and `parameters` stay for Binds still on the wire under the old name. - pub(crate) fn reset_for_reprepare(&mut self, prepared_statement_id: u64) { - self.status = Status::Pending; - self.error_response = None; - self.signature - .set_prepared_statement_name(prepared_statement_id); - } - pub(crate) fn check_for_duplicate_fields(&mut self) { if !self.needs_duplicate_check { return; diff --git a/src/sql_jsc/postgres/Signature.rs b/src/sql_jsc/postgres/Signature.rs index 0658f81b9711..3669e5f406f1 100644 --- a/src/sql_jsc/postgres/Signature.rs +++ b/src/sql_jsc/postgres/Signature.rs @@ -34,6 +34,17 @@ impl Signature { self.prepared_statement_name = v.into_boxed_slice(); } + /// The same query under another server-side name. + pub(crate) fn renamed(&self, prepared_statement_id: u64) -> Signature { + let mut signature = Signature { + fields: self.fields.clone(), + name: self.name.clone(), + prepared_statement_name: Box::default(), + }; + signature.set_prepared_statement_name(prepared_statement_id); + signature + } + // JSError (from QueryBindingIterator / // Tag::from_js), OOM, and InvalidQueryBinding are collapsed to the // crate-wide `crate::Error`. diff --git a/test/js/sql/postgres-prepared-statement-invalidation.test.ts b/test/js/sql/postgres-prepared-statement-invalidation.test.ts index 5785d75f3d31..368ba7784335 100644 --- a/test/js/sql/postgres-prepared-statement-invalidation.test.ts +++ b/test/js/sql/postgres-prepared-statement-invalidation.test.ts @@ -16,6 +16,7 @@ import { pgAuthenticationOk, pgBindComplete, pgBindParameters, + pgBindResultFormats, pgCommandComplete, pgDataRow, pgErrorResponse, @@ -743,3 +744,138 @@ test("postgres: a 26000 after BindComplete is surfaced and the statement stays c server.close(); } }); + +// The reply to a re-prepare can arrive split across reads between +// ParseComplete and RowDescription. A query issued there finds the statement +// Prepared and is written at once. Its Bind must not ask for the column +// formats of the statement that the server invalidated: the server then sends +// a value in one format and the client reads it in the other. +type Column = { name: string; typeOid: number; text: string; binary: Buffer }; + +function int4(value: number): Buffer { + const bytes = Buffer.alloc(4); + bytes.writeInt32BE(value); + return bytes; +} + +const tick = () => new Promise(resolve => setImmediate(resolve)); + +test.each([ + { + change: "ALTER COLUMN TYPE", + before: [{ name: "a", typeOid: 25 /* text */, text: "42", binary: Buffer.from("42") }], + after: [{ name: "a", typeOid: 23 /* int4 */, text: "42", binary: int4(42) }], + row: { a: 42 }, + }, + { + change: "ADD COLUMN", + before: [ + { name: "a", typeOid: 23, text: "1", binary: int4(1) }, + { name: "b", typeOid: 25, text: "x", binary: Buffer.from("x") }, + ], + after: [ + { name: "a", typeOid: 23, text: "1", binary: int4(1) }, + { name: "b", typeOid: 25, text: "x", binary: Buffer.from("x") }, + { name: "c", typeOid: 23, text: "3", binary: int4(3) }, + ], + row: { a: 1, b: "x", c: 3 }, + }, +] satisfies { change: string; before: Column[]; after: Column[]; row: object }[])( + "postgres: a query issued before the RowDescription of a re-prepare asks for no stale column format ($change)", + async ({ before, after, row }) => { + let schema: Column[] = before; + let version = 1; + const parsedUnder = new Map(); // statement name -> schema version + let portal: number[] | null = null; // the format of each column; null after a failed Bind + let holdNextDescribe = false; + let held = false; + let windowOpen = false; + let bindsInWindow = 0; + const describeHeld = Promise.withResolvers(); + // The mock does what the server does: a statement parsed under an older + // schema answers 0A000 to each Bind, the count of result formats must be + // 0, 1 or the column count, and a value goes out in the format asked for. + const mock = await pgMockServer((type, body) => { + switch (type) { + case "P": + parsedUnder.set(body.subarray(0, body.indexOf(0)).toString("utf-8"), version); + return pgParseComplete(); + case "D": + if (!holdNextDescribe) return [pgParameterDescription([]), pgRowDescription(schema)]; + holdNextDescribe = false; + held = true; + describeHeld.resolve(); + return [pgParameterDescription([]), pgHold, pgRowDescription(schema)]; + case "B": { + if (windowOpen) bindsInWindow++; + portal = null; + const afterPortal = body.indexOf(0) + 1; + const name = body.subarray(afterPortal, body.indexOf(0, afterPortal)).toString("utf-8"); + if (parsedUnder.get(name) !== version) { + return pgErrorResponse({ + S: "ERROR", + C: "0A000", + M: "cached plan must not change result type", + R: "RevalidateCachedQuery", + }); + } + const formats = pgBindResultFormats(body); + if (formats.length > 1 && formats.length !== schema.length) { + return pgErrorResponse({ + S: "ERROR", + C: "08P01", + M: `bind message has ${formats.length} result formats but query has ${schema.length} columns`, + R: "PortalSetResultFormat", + }); + } + portal = schema.map((_, i) => (formats.length === 0 ? 0 : formats.length === 1 ? formats[0] : formats[i])); + return pgBindComplete(); + } + case "E": { + if (portal === null) return; + const formats = portal; + const values = schema.map((column, i) => (formats[i] === 1 ? column.binary : Buffer.from(column.text))); + return [pgDataRow(values), pgCommandComplete("SELECT 1")]; + } + case "S": + portal = null; + // The batch of the re-prepare ends here. A Bind after it is a new query. + if (held) windowOpen = true; + return pgReadyForQuery(); + } + }); + + try { + await using sql = new SQL({ url: `postgres://u@127.0.0.1:${mock.port}/db`, max: 1, idleTimeout: 5 }); + const q = () => sql`select * from t`; + await q(); + // The cached statement now has the columns of `before`. + await q(); + + schema = after; + version = 2; + holdNextDescribe = true; + const first = q().execute(); + await describeHeld.promise; + // The client gives no signal when it has read ParseComplete and + // ParameterDescription, so the second query waits many turns of the + // loop. `bindsInWindow` below proves that it was written in the window. + let second: Promise | undefined; + for (let turn = 0; turn < 20_000 && bindsInWindow === 0; turn++) { + await tick(); + if (turn === 1_000) second = q().execute(); + } + held = false; + windowOpen = false; + mock.release(); + + expect({ first: await first, second: await second, bindsInWindow }).toEqual({ + first: [row], + second: [row], + bindsInWindow: 1, + }); + } finally { + mock.server.close(); + } + }, +); diff --git a/test/js/sql/wire-frames.ts b/test/js/sql/wire-frames.ts index af2030885250..b733e72c44fa 100644 --- a/test/js/sql/wire-frames.ts +++ b/test/js/sql/wire-frames.ts @@ -266,6 +266,24 @@ export function pgBindParameters(body: Buffer): (Buffer | null)[] { return params; } +/** The result-column format codes of a frontend Bind message body (0 = text, 1 = binary). */ +export function pgBindResultFormats(body: Buffer): number[] { + let o = body.indexOf(0) + 1; // portal name + o = body.indexOf(0, o) + 1; // statement name + o += 2 + 2 * body.readUInt16BE(o); // parameter format codes + const params = body.readUInt16BE(o); + o += 2; + for (let i = 0; i < params; i++) { + const len = body.readInt32BE(o); + o += 4; + if (len > 0) o += len; + } + const formats: number[] = []; + const count = body.readUInt16BE(o); + for (let i = 0; i < count; i++) formats.push(body.readUInt16BE(o + 2 + 2 * i)); + return formats; +} + // Frontend messages as a client writes them. The mocks only read these; the builders let a test state the exact // bytes it expects on the wire. From f0c2d58f1b9d2e8dfbd60de27884cf6a45c01968 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 27 Sep 2026 11:54:11 +0000 Subject: [PATCH 11/12] sql(postgres): shorten the replace_statement doc comment --- src/sql_jsc/postgres/PostgresSQLConnection.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index ad44c1c6bc85..01a246f4760d 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -1599,10 +1599,8 @@ impl PostgresSQLConnection { }); } - /// Give `request`, and each queued request that holds the same evicted statement - /// and is not on the wire, the statement that takes its place: the one a - /// pipelined sibling or a later query already cached, or a new one. The evicted - /// statement keeps the description the requests on the wire were bound with. + /// Point `request`, and every queued request that holds the same evicted + /// statement, at the cached replacement, or at a new one under a new name. fn replace_statement(&self, request: &PostgresSQLQuery) { let Some(invalidated) = request.statement.get().clone() else { return; From 214866d94b1482261e0b94cf05f54d863f87f793 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 27 Sep 2026 12:35:51 +0000 Subject: [PATCH 12/12] test(sql): fail fast when the re-prepare Describe never comes --- ...postgres-prepared-statement-invalidation.test.ts | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/test/js/sql/postgres-prepared-statement-invalidation.test.ts b/test/js/sql/postgres-prepared-statement-invalidation.test.ts index 368ba7784335..de188cd09e68 100644 --- a/test/js/sql/postgres-prepared-statement-invalidation.test.ts +++ b/test/js/sql/postgres-prepared-statement-invalidation.test.ts @@ -856,7 +856,18 @@ test.each([ version = 2; holdNextDescribe = true; const first = q().execute(); - await describeHeld.promise; + // Without a re-prepare `first` settles and no second Describe comes. + await Promise.race([ + describeHeld.promise, + first.then( + () => { + throw new Error("query settled before the re-prepare Describe"); + }, + e => { + throw e; + }, + ), + ]); // The client gives no signal when it has read ParseComplete and // ParameterDescription, so the second query waits many turns of the // loop. `bindsInWindow` below proves that it was written in the window.