From acec2d8d9d81ddb696e160d9b5a59867d95d8500 Mon Sep 17 00:00:00 2001 From: robobun Date: Sun, 5 Jul 2026 10:33:46 +0000 Subject: [PATCH 01/34] sql: implement Query.cancel() for postgres The native cancel hook was an empty stub, so cancel() never wrote anything: an in-flight query ran to completion and resolved with its rows, and a query cancelled before it was dispatched never settled. A backend running a query reads nothing from its connection until the query finishes, so cancel() now opens a second connection and sends a CancelRequest built from the BackendKeyData the server already handed out. The backend answers the original connection with SQLSTATE 57014, which rejects the query through the existing ErrorResponse path. A query that is queued on a connection but whose bytes are not on the wire is failed locally instead: a CancelRequest there would stop whatever the backend is actually running. A query that was never dispatched is rejected with ERR_POSTGRES_QUERY_CANCELLED. --- docs/runtime/sql.mdx | 11 +- packages/bun-types/sql.d.ts | 6 +- src/js/internal/sql/postgres.ts | 40 +++++ src/js/internal/sql/query.ts | 22 ++- src/js/internal/sql/shared.ts | 7 + src/runtime/api/sql.classes.ts | 8 +- src/sql/postgres/AnyPostgresError.rs | 1 + src/sql/postgres/protocol/BackendKeyData.rs | 16 ++ src/sql_jsc/jsc.rs | 5 +- src/sql_jsc/postgres/PostgresSQLQuery.rs | 56 +++++- src/sql_jsc/postgres/error_jsc.rs | 1 + test/js/sql/postgres-query-cancel.test.ts | 190 ++++++++++++++++++++ test/js/sql/wire-frames.ts | 17 ++ 13 files changed, 364 insertions(+), 16 deletions(-) create mode 100644 test/js/sql/postgres-query-cancel.test.ts diff --git a/docs/runtime/sql.mdx b/docs/runtime/sql.mdx index 475df9958dcf..2cab3097c59d 100644 --- a/docs/runtime/sql.mdx +++ b/docs/runtime/sql.mdx @@ -440,14 +440,21 @@ const result = await sql.unsafe("SELECT " + dangerous + " FROM users WHERE id = ### Execute and Cancelling Queries Queries are lazy: they only start executing when awaited or run with `.execute()`. -To cancel a running query, call `cancel()` on the query object. +To cancel a running query, call `cancel()` on the query object. A cancelled query +rejects instead of resolving. ```ts -const query = sql`SELECT * FROM users`.execute(); +const query = sql`SELECT pg_sleep(30)`.execute(); setTimeout(() => query.cancel(), 100); + +// PostgresError: canceling statement due to user request (SQLSTATE 57014) await query; ``` +PostgreSQL can only stop a running query from a separate connection, so `cancel()` +opens one and sends a `CancelRequest` on it. A query that has not reached the +server yet never runs at all, and rejects with `ERR_POSTGRES_QUERY_CANCELLED`. + --- ## Database Environment Variables diff --git a/packages/bun-types/sql.d.ts b/packages/bun-types/sql.d.ts index b6d524b0cbba..d65ce2db2929 100644 --- a/packages/bun-types/sql.d.ts +++ b/packages/bun-types/sql.d.ts @@ -428,7 +428,11 @@ declare module "bun" { cancelled: boolean; /** - * Cancels the executing query + * Cancels the query and rejects its promise. A query the server is already + * running is stopped with a `CancelRequest` sent on a second connection, + * and rejects with whatever the server reports (PostgreSQL: SQLSTATE + * 57014). A query that never reached the server rejects with + * `ERR_POSTGRES_QUERY_CANCELLED`. */ cancel(): Query; diff --git a/src/js/internal/sql/postgres.ts b/src/js/internal/sql/postgres.ts index 897f6526c82b..aa1efa26e406 100644 --- a/src/js/internal/sql/postgres.ts +++ b/src/js/internal/sql/postgres.ts @@ -30,6 +30,10 @@ const { const cmds = ["", "INSERT", "DELETE", "UPDATE", "MERGE", "SELECT", "MOVE", "FETCH", "COPY"]; +// How long the connection opened for a CancelRequest waits for the backend to +// close it before giving up. +const CANCEL_REQUEST_TIMEOUT_SECONDS = 5; + const escapeBackslash = /\\/g; const escapeQuote = /"/g; @@ -416,6 +420,42 @@ class PostgresAdapter return '"' + str.replaceAll('"', '""').replaceAll(".", '"."') + '"'; } + /** + * A backend running a query reads nothing until it finishes, so the only way + * to stop it is a CancelRequest on a second connection. The backend handles + * that message before authentication and before any SSL negotiation, and it + * carries no credentials beyond the pid/secret pair the server itself handed + * out in BackendKeyData, so the cancel connection stays plaintext, the way + * libpq's PQcancel() sends it. + */ + sendCancelRequest(request: Uint8Array): void { + const { path, hostname, port } = this.connectionInfo; + const address = path ? { unix: path } : { hostname, port }; + + Bun.connect({ + ...address, + socket: { + open(socket) { + socket.write(request); + socket.flush(); + // The backend closes the connection once it has acted on the request. + // Bound the wait so a peer that never answers cannot pin the event loop. + socket.timeout(CANCEL_REQUEST_TIMEOUT_SECONDS); + }, + timeout(socket) { + socket.end(); + }, + // The backend never replies to a CancelRequest, but Bun.connect requires + // a reader. + data() {}, + // Cancelling is best effort: a request that never reaches the server + // just leaves the query running, which is what happens today anyway. + connectError() {}, + error() {}, + }, + }); + } + connectionClosedError() { return new PostgresError("Connection closed", { code: "ERR_POSTGRES_CONNECTION_CLOSED", diff --git a/src/js/internal/sql/query.ts b/src/js/internal/sql/query.ts index 258f10f05922..5993d157374d 100644 --- a/src/js/internal/sql/query.ts +++ b/src/js/internal/sql/query.ts @@ -15,7 +15,12 @@ const PublicPromise = Promise; export interface BaseQueryHandle { done?(): void; - cancel?(): void; + /** + * Abort a query the handle already dispatched. Returns the request bytes the + * adapter has to deliver out-of-band (Postgres sends a CancelRequest on a + * second connection), or undefined when nothing has to reach the server. + */ + cancel?(): Uint8Array | undefined; setMode(mode: SQLQueryResultMode): void; run(connection: Connection, query: Query): void | Promise; } @@ -218,11 +223,18 @@ class Query> extends PublicPromise { this[_queryStatus] |= SQLQueryStatus.cancelled; - if (status & SQLQueryStatus.executed) { - const handle = this.#getQueryHandle(); + if (!(status & SQLQueryStatus.executed)) { + // Never dispatched, so no connection will ever settle this promise. + this.reject(this[_adapter].queryCancelledError()); + return this; + } + + const handle = this.#getQueryHandle(); - if (handle) { - handle.cancel?.(); + if (handle) { + const cancelRequest = handle.cancel?.(); + if (cancelRequest) { + this[_adapter].sendCancelRequest?.(cancelRequest); } } diff --git a/src/js/internal/sql/shared.ts b/src/js/internal/sql/shared.ts index 21c781812aa6..1e2302961c7a 100644 --- a/src/js/internal/sql/shared.ts +++ b/src/js/internal/sql/shared.ts @@ -2140,6 +2140,13 @@ export interface DatabaseAdapter { connectionClosedError(): Error; queryCancelledError(): Error; invalidTransactionStateError(message: string): Error; + + /** + * Deliver a `Query.cancel()` request that cannot travel on the query's own + * connection, because that connection is busy running the query being + * cancelled. Postgres opens a second connection to the same server for it. + */ + sendCancelRequest?(request: Uint8Array): void; } export default { diff --git a/src/runtime/api/sql.classes.ts b/src/runtime/api/sql.classes.ts index 5ab213c7590d..c3ea03fdd5b0 100644 --- a/src/runtime/api/sql.classes.ts +++ b/src/runtime/api/sql.classes.ts @@ -92,7 +92,13 @@ for (const type of types) { length: 1, }, }, - values: ["pendingValue", "target", "columns", "binding"], + // Postgres cancels a running query by sending a CancelRequest on a + // second connection, so its query handle has to remember which + // connection it was dispatched to. + values: + type === "PostgresSQL" + ? ["pendingValue", "target", "columns", "binding", "connection"] + : ["pendingValue", "target", "columns", "binding"], estimatedSize: true, }), ); diff --git a/src/sql/postgres/AnyPostgresError.rs b/src/sql/postgres/AnyPostgresError.rs index 26cca6ac063d..341f4e88758c 100644 --- a/src/sql/postgres/AnyPostgresError.rs +++ b/src/sql/postgres/AnyPostgresError.rs @@ -31,6 +31,7 @@ pub enum AnyPostgresError { OutOfMemory, Overflow, PBKDFD2, + QueryCancelled, SASL_SIGNATURE_MISMATCH, SASL_SIGNATURE_INVALID_BASE64, ShortRead, diff --git a/src/sql/postgres/protocol/BackendKeyData.rs b/src/sql/postgres/protocol/BackendKeyData.rs index df6dcdb58ed7..a5d2c9b954e1 100644 --- a/src/sql/postgres/protocol/BackendKeyData.rs +++ b/src/sql/postgres/protocol/BackendKeyData.rs @@ -1,6 +1,10 @@ use super::new_reader::NewReader; use crate::postgres::AnyPostgresError; +/// Protocol §55.2.3: the request code a CancelRequest carries in place of the +/// protocol version, `(1234 << 16) | 5678`. +const CANCEL_REQUEST_CODE: u32 = 80877102; + #[derive(Default)] pub struct BackendKeyData { pub process_id: u32, @@ -14,6 +18,18 @@ impl BackendKeyData { Self::decode_internal(NewReader { wrapped: context }) } + /// Protocol §55.2.3 CancelRequest: `Int32(16) Int32(80877102) Int32(pid) Int32(secret)`. + /// It has no message-type byte because it is only ever sent as the first + /// message of a *separate* connection, which the backend then closes. + pub fn cancel_request(&self) -> [u8; 16] { + let mut packet = [0u8; 16]; + packet[0..4].copy_from_slice(&16u32.to_be_bytes()); + packet[4..8].copy_from_slice(&CANCEL_REQUEST_CODE.to_be_bytes()); + packet[8..12].copy_from_slice(&self.process_id.to_be_bytes()); + packet[12..16].copy_from_slice(&self.secret_key.to_be_bytes()); + packet + } + pub fn decode_internal( mut reader: NewReader, ) -> Result { diff --git a/src/sql_jsc/jsc.rs b/src/sql_jsc/jsc.rs index 86f1698eefd1..5726e36c8a87 100644 --- a/src/sql_jsc/jsc.rs +++ b/src/sql_jsc/jsc.rs @@ -29,8 +29,8 @@ use core::ptr::NonNull; pub use bun_jsc::{ ArrayBuffer, CallFrame, CoerceTo, ErrorBuilder, ErrorCode, ExternColumnIdentifier, ExternColumnIdentifierValue, GlobalRef, JSArrayIterator, JSCell, JSGlobalObject, JSObject, - JSType, JSValue, JsCell, JsError, JsRef, JsResult, MarkedArgumentBuffer, StringJsc, - StrongOptional, ThrowFmtArgs, ZigStringJsc, bun_string_jsc, host_fn, + JSType, JSUint8Array, JSValue, JsCell, JsError, JsRef, JsResult, MarkedArgumentBuffer, + StringJsc, StrongOptional, ThrowFmtArgs, ZigStringJsc, bun_string_jsc, host_fn, }; /// Re-export — `bun_jsc` now defines `IntegerRange` at its crate root and the @@ -623,6 +623,7 @@ pub mod codegen { impl_js_class { binding, columns, + connection, pendingValue, target } diff --git a/src/sql_jsc/postgres/PostgresSQLQuery.rs b/src/sql_jsc/postgres/PostgresSQLQuery.rs index 78a478263d9e..4488882befad 100644 --- a/src/sql_jsc/postgres/PostgresSQLQuery.rs +++ b/src/sql_jsc/postgres/PostgresSQLQuery.rs @@ -277,6 +277,7 @@ impl PostgresSQLQuery { js::binding_set_cached(this_value, global_object, JSValue::ZERO); js::pending_value_set_cached(this_value, global_object, JSValue::ZERO); js::target_set_cached(this_value, global_object, JSValue::ZERO); + js::connection_set_cached(this_value, global_object, JSValue::ZERO); } pub fn on_result( @@ -471,7 +472,8 @@ impl PostgresSQLQuery { // duration of this call, satisfying the `ParentRef` outlives-holder // invariant. R-2: shared borrow — every connection field accessed below is // `Cell`/`JsCell`. - let Some(connection) = postgres_sql_connection::js::from_js_ref(arguments[0]) else { + let connection_value = arguments[0]; + let Some(connection) = postgres_sql_connection::js::from_js_ref(connection_value) else { return Err( global_object.throw(format_args!("connection must be a PostgresSQLConnection")) ); @@ -566,6 +568,7 @@ impl PostgresSQLQuery { this.this_value.with_mut(|r| r.upgrade(global_object)); js::target_set_cached(this_value, global_object, query); + js::connection_set_cached(this_value, global_object, connection_value); if this.status.get() == Status::Running { connection.flush_data_and_reset_timeout(); } else { @@ -837,6 +840,7 @@ impl PostgresSQLQuery { this.this_value.with_mut(|r| r.upgrade(global_object)); js::target_set_cached(this_value, global_object, query); + js::connection_set_cached(this_value, global_object, connection_value); if did_write { connection.flush_data_and_reset_timeout(); } else { @@ -848,15 +852,57 @@ impl PostgresSQLQuery { Ok(JSValue::UNDEFINED) } + /// Returns the CancelRequest packet the caller must deliver on a second + /// connection, or `undefined` when there is nothing for the server to stop. pub fn do_cancel( this: &Self, global_object: &JSGlobalObject, callframe: &CallFrame, ) -> JsResult { - let _ = callframe; - let _ = global_object; - let _ = this; + let this_value = callframe.this(); + // No connection cached means `run()` never bound this query to one, so + // the pool still owes it a connection (or it already finished). Either + // way there is nothing on the wire to cancel. + let Some(connection_value) = js::connection_get_cached(this_value) else { + return Ok(JSValue::UNDEFINED); + }; + let Some(connection) = postgres_sql_connection::js::from_js_ref(connection_value) else { + return Ok(JSValue::UNDEFINED); + }; - Ok(JSValue::UNDEFINED) + match this.status.get() { + // Queued behind another request: none of this query's Bind/Execute + // has been written, so a CancelRequest would stop whatever the + // backend is actually running. Fail it here instead. The entry stays + // in the connection's FIFO until advance() discards it, exactly like + // a request whose statement failed to prepare. + Status::Pending => { + let err = postgres_error_to_js( + global_object, + Some(b"Query cancelled"), + AnyPostgresError::QueryCancelled, + ); + this.on_js_error(err, global_object); + Ok(JSValue::UNDEFINED) + } + Status::Binding | Status::Running | Status::PartialResponse => { + // Copy the key out before allocating into the JS heap, so no + // `JsCell` borrow is live across a call that can re-enter. + let (process_id, packet) = { + let key = connection.backend_key_data.get(); + (key.process_id, key.cancel_request()) + }; + // The server never sent BackendKeyData, so it cannot be asked to + // cancel anything. The query keeps running. + if process_id == 0 { + return Ok(JSValue::UNDEFINED); + } + Ok(crate::jsc::JSUint8Array::from_bytes_copy( + global_object, + &packet, + )) + } + Status::Success | Status::Fail => Ok(JSValue::UNDEFINED), + } } } diff --git a/src/sql_jsc/postgres/error_jsc.rs b/src/sql_jsc/postgres/error_jsc.rs index 84c687de1d06..c44110067982 100644 --- a/src/sql_jsc/postgres/error_jsc.rs +++ b/src/sql_jsc/postgres/error_jsc.rs @@ -77,6 +77,7 @@ pub(crate) fn postgres_error_to_js( NullsInArrayNotSupportedYet => b"ERR_POSTGRES_NULLS_IN_ARRAY_NOT_SUPPORTED_YET", Overflow => b"ERR_POSTGRES_OVERFLOW", PBKDFD2 => b"ERR_POSTGRES_AUTHENTICATION_FAILED_PBKDF2", + QueryCancelled => b"ERR_POSTGRES_QUERY_CANCELLED", SASL_SIGNATURE_MISMATCH => b"ERR_POSTGRES_SASL_SIGNATURE_MISMATCH", SASL_SIGNATURE_INVALID_BASE64 => b"ERR_POSTGRES_SASL_SIGNATURE_INVALID_BASE64", TLSNotAvailable => b"ERR_POSTGRES_TLS_NOT_AVAILABLE", diff --git a/test/js/sql/postgres-query-cancel.test.ts b/test/js/sql/postgres-query-cancel.test.ts new file mode 100644 index 000000000000..e7261e425689 --- /dev/null +++ b/test/js/sql/postgres-query-cancel.test.ts @@ -0,0 +1,190 @@ +// A backend that is running a query reads nothing from its connection until the +// query finishes, so the only way to stop it is the CancelRequest message on a +// *second* connection (protocol §55.2.3). Asserting those bytes, and asserting +// that they are NOT sent for a query the backend never started, needs a server +// that answers on demand, which is why this uses a scripted one instead of +// describeWithContainer. All wire bytes come from test/js/sql/wire-frames.ts. +// +// Query.cancel() used to be a no-op for Postgres: nothing was ever written, so a +// cancelled query ran to completion and resolved with its rows, and a query +// cancelled before it was dispatched never settled at all. +import { SQL } from "bun"; +import { expect, test } from "bun:test"; +import net from "node:net"; +import { + pgAuthenticationOk, + pgBackendKeyData, + pgCancelRequest, + pgCommandComplete, + pgDataRow, + pgErrorResponse, + pgReadyForQuery, + pgRowDescription, +} from "./wire-frames"; + +const PROCESS_ID = 4242; +const SECRET_KEY = 13371337; +const TEXT_OID = 25; + +/** + * Completes the handshake (advertising BackendKeyData) and then leaves every + * query unanswered, the way a backend stuck inside pg_sleep() would. The test + * drives the reply itself. The connection a CancelRequest arrives on is always + * the second one, because the first is busy running the query. + */ +async function hangingBackend() { + const queryReceived = Promise.withResolvers(); + const cancelPacket = Promise.withResolvers(); + const sockets = new Set(); + let queryConnection: net.Socket | undefined; + let connections = 0; + + const server = net.createServer(socket => { + sockets.add(socket); + socket.on("close", () => sockets.delete(socket)); + socket.on("error", () => {}); + + if (++connections > 1) { + let buffered = Buffer.alloc(0); + socket.on("data", data => { + buffered = Buffer.concat([buffered, data]); + if (buffered.length < 16) return; + cancelPacket.resolve(buffered); + // A real backend acts on the CancelRequest and hangs up. + socket.end(); + }); + return; + } + + queryConnection = socket; + let handshaken = false; + socket.on("data", () => { + if (!handshaken) { + handshaken = true; + socket.write( + Buffer.concat([pgAuthenticationOk(), pgBackendKeyData(PROCESS_ID, SECRET_KEY), pgReadyForQuery()]), + ); + return; + } + queryReceived.resolve(); + }); + }); + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as net.AddressInfo; + + return { + url: `postgres://postgres@127.0.0.1:${port}/postgres`, + queryReceived: queryReceived.promise, + cancelPacket: cancelPacket.promise, + get connections() { + return connections; + }, + reply(...frames: Buffer[]) { + queryConnection!.write(Buffer.concat(frames)); + }, + async [Symbol.asyncDispose]() { + for (const socket of sockets) socket.destroy(); + await new Promise(resolve => server.close(() => resolve())); + }, + }; +} + +// Both the extended protocol (the default) and the simple protocol put the +// query on the wire before the backend answers anything, so both are +// cancellable the same way. +const protocols: [name: string, start: (query: any) => any][] = [ + ["extended", query => query.execute()], + ["simple", query => query.simple().execute()], +]; + +test.each(protocols)("cancel() on a running %s query sends a CancelRequest", async (_name, start) => { + await using backend = await hangingBackend(); + await using sql = new SQL({ url: backend.url, max: 1, connectionTimeout: 5 }); + + const query = start(sql`select pg_sleep(10)`); + const settled = query.then( + (rows: unknown) => rows, + (err: any) => err, + ); + await backend.queryReceived; + + query.cancel(); + + // The CancelRequest names the backend by the pid/secret pair it handed out in + // BackendKeyData, on a connection of its own. + expect(await backend.cancelPacket).toEqual(pgCancelRequest(PROCESS_ID, SECRET_KEY)); + expect(backend.connections).toBe(2); + + // A real backend answers the cancelled query on its own connection, with + // SQLSTATE 57014 (query_canceled). + backend.reply( + pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), + pgReadyForQuery(), + ); + + const err = await settled; + expect({ name: err.name, code: err.code, errno: err.errno, message: err.message }).toEqual({ + name: "PostgresError", + code: "ERR_POSTGRES_SERVER_ERROR", + errno: "57014", + message: "canceling statement due to user request", + }); +}); + +test("cancel() before the query is dispatched rejects it instead of hanging", async () => { + await using backend = await hangingBackend(); + await using sql = new SQL({ url: backend.url, max: 1, connectionTimeout: 5 }); + + // Tagged templates are lazy: nothing has been sent, and nothing ever will be, + // so cancel() has to settle the promise itself. + const query = sql`select 1`; + query.cancel(); + + const err = await query.catch((e: any) => e); + expect({ name: err.name, code: err.code, message: err.message }).toEqual({ + name: "PostgresError", + code: "ERR_POSTGRES_QUERY_CANCELLED", + message: "Query cancelled", + }); + // Never even asked the pool for a connection. + expect(backend.connections).toBe(0); +}); + +test("cancel() on a queued query does not cancel the one the backend is running", async () => { + await using backend = await hangingBackend(); + await using sql = new SQL({ url: backend.url, max: 1, connectionTimeout: 5 }); + + const running = sql`select 'kept'`.simple().execute(); + const runningSettled = running.then( + rows => rows, + err => err, + ); + await backend.queryReceived; + + // Dispatched onto the same connection, but behind the running query: none of + // its bytes are on the wire, so a CancelRequest would stop the wrong query. + const queued = sql`select 'cancelled'`.simple().execute(); + const queuedSettled = queued.then( + rows => rows, + err => err, + ); + queued.cancel(); + + const err = await queuedSettled; + expect({ name: err.name, code: err.code, message: err.message }).toEqual({ + name: "PostgresError", + code: "ERR_POSTGRES_QUERY_CANCELLED", + message: "Query cancelled", + }); + + backend.reply( + pgRowDescription([{ name: "v", typeOid: TEXT_OID }]), + pgDataRow([Buffer.from("kept")]), + pgCommandComplete("SELECT 1"), + pgReadyForQuery(), + ); + + expect(await runningSettled).toEqual([{ v: "kept" }]); + // No second connection was opened, so nothing was cancelled on the server. + expect(backend.connections).toBe(1); +}); diff --git a/test/js/sql/wire-frames.ts b/test/js/sql/wire-frames.ts index b4bfab875bcc..84e129700ace 100644 --- a/test/js/sql/wire-frames.ts +++ b/test/js/sql/wire-frames.ts @@ -70,6 +70,23 @@ export function pgSSLResponse(answer: "S" | "N"): Buffer { return Buffer.from(answer, "latin1"); } +// PostgreSQL FE/BE protocol §55.2.3 CancelRequest: Int32(16) Int32(80877102) Int32(pid) Int32(secret) +// Sent by the client as the first (and only) message of a second connection; it +// has no message-type byte, same as the startup packet. +export function pgCancelRequest(processId: number, secretKey: number): Buffer { + const buf = Buffer.alloc(16); + buf.writeInt32BE(16, 0); + buf.writeInt32BE(80877102, 4); // 0x04d2162e + buf.writeInt32BE(processId, 8); + buf.writeInt32BE(secretKey, 12); + return buf; +} + +// PostgreSQL FE/BE protocol §55.7 BackendKeyData: Byte1('K') Int32(12) Int32(pid) Int32(secret) +export function pgBackendKeyData(processId: number, secretKey: number): Buffer { + return pgRaw("K", Buffer.concat([pgInt32(processId), pgInt32(secretKey)])); +} + // PostgreSQL FE/BE protocol §55.7 AuthenticationOk: Byte1('R') Int32(8) Int32(0) export function pgAuthenticationOk(): Buffer { const buf = Buffer.alloc(9); From d920eabaf7ff607a4c5cc8f0c790da6adee16a78 Mon Sep 17 00:00:00 2001 From: robobun Date: Sun, 5 Jul 2026 11:41:44 +0000 Subject: [PATCH 02/34] sql: only send a postgres CancelRequest for the query the backend is running A CancelRequest names the backend process, not a statement, so it stops whatever that backend is executing: the request at the head of the connection's FIFO. do_run()'s Prepared arm writes a query's Bind/Execute as soon as can_pipeline() allows, which happens while an earlier query is still running, so cancelling the pipelined query sent a CancelRequest that killed the query ahead of it instead. Check that the request is the head of the FIFO before asking the server to stop it. A request behind the head is settled locally, but the two cases differ: a Pending request has nothing on the wire and is failed, so advance() discards it instead of writing it, while a pipelined request is already on the socket and the backend will answer it no matter what, so its promise is rejected in place and the FIFO entry stays to consume those answers in order. Marking it failed would make advance() discard it and the next BindComplete would land on the wrong request. --- packages/bun-types/sql.d.ts | 11 +- src/sql_jsc/postgres/PostgresSQLConnection.rs | 9 + src/sql_jsc/postgres/PostgresSQLQuery.rs | 101 ++++++++---- test/js/sql/postgres-query-cancel.test.ts | 155 +++++++++++++++--- test/js/sql/wire-frames.ts | 34 ++++ 5 files changed, 251 insertions(+), 59 deletions(-) diff --git a/packages/bun-types/sql.d.ts b/packages/bun-types/sql.d.ts index d65ce2db2929..44b213ee508f 100644 --- a/packages/bun-types/sql.d.ts +++ b/packages/bun-types/sql.d.ts @@ -428,11 +428,12 @@ declare module "bun" { cancelled: boolean; /** - * Cancels the query and rejects its promise. A query the server is already - * running is stopped with a `CancelRequest` sent on a second connection, - * and rejects with whatever the server reports (PostgreSQL: SQLSTATE - * 57014). A query that never reached the server rejects with - * `ERR_POSTGRES_QUERY_CANCELLED`. + * Cancels the query and rejects its promise with the adapter's + * query-cancelled error (for example `ERR_POSTGRES_QUERY_CANCELLED`). + * + * For PostgreSQL, a query the backend has already started is stopped with a + * `CancelRequest` sent on a second connection, and rejects with whatever the + * server reports instead (SQLSTATE 57014). */ cancel(): Query; diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index 5ff3a0cbebf4..9026616f4f47 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -1572,6 +1572,15 @@ impl PostgresSQLConnection { )) } + /// True when `request` is the head of the FIFO, i.e. the one the backend is + /// executing right now. Requests behind the head have either not been + /// written at all, or were pipelined onto the wire and the backend has not + /// reached them yet. + pub fn is_current_request(&self, request: *const PostgresSQLQuery) -> bool { + let q = self.requests.get(); + q.readable_length() > 0 && core::ptr::eq(q.peek_item(0).cast_const(), request) + } + /// Drop the queue-held intrusive ref on `request` and pop one entry from /// the FIFO head. One audited `unsafe` here replaces the per-site /// `unsafe { PostgresSQLQuery::deref(ptr) }; self.requests.with_mut(|q| q.discard(1));` diff --git a/src/sql_jsc/postgres/PostgresSQLQuery.rs b/src/sql_jsc/postgres/PostgresSQLQuery.rs index 4488882befad..4b1f22c23233 100644 --- a/src/sql_jsc/postgres/PostgresSQLQuery.rs +++ b/src/sql_jsc/postgres/PostgresSQLQuery.rs @@ -239,7 +239,36 @@ impl PostgresSQLQuery { let Some(target_value) = self.get_target(global_object, true) else { return; }; + self.run_reject_callback(global_object, this_value, target_value, err); + } + + /// Reject the promise of a request whose Bind/Execute is already on the wire. + /// + /// Unlike [`on_js_error`](Self::on_js_error) this leaves `status`, `target` + /// and the strong `this_value` alone: the backend is going to answer this + /// request no matter what, and the connection has to keep the FIFO entry to + /// consume those answers in order. `Status::Fail` would make `advance()` + /// discard the entry and the next BindComplete would land on the wrong + /// request. The request then finishes down the normal path, where + /// `Query.resolve()` on an already rejected promise is a no-op. + pub fn reject_in_place(&self, err: JSValue, global_object: &JSGlobalObject) { + let _deref = self.ref_guard(); + let Some(this_value) = self.this_value.get().try_get() else { + return; + }; + let Some(target_value) = self.get_target(global_object, false) else { + return; + }; + self.run_reject_callback(global_object, this_value, target_value, err); + } + fn run_reject_callback( + &self, + global_object: &JSGlobalObject, + this_value: JSValue, + target_value: JSValue, + err: JSValue, + ) { // SAFETY: JS-thread only; short-lived `&mut` to the singleton VM, no other live borrow. let vm = crate::jsc::VirtualMachine::get().as_mut(); let function = vm @@ -870,39 +899,49 @@ impl PostgresSQLQuery { return Ok(JSValue::UNDEFINED); }; - match this.status.get() { - // Queued behind another request: none of this query's Bind/Execute - // has been written, so a CancelRequest would stop whatever the - // backend is actually running. Fail it here instead. The entry stays - // in the connection's FIFO until advance() discards it, exactly like - // a request whose statement failed to prepare. - Status::Pending => { - let err = postgres_error_to_js( - global_object, - Some(b"Query cancelled"), - AnyPostgresError::QueryCancelled, - ); + let status = this.status.get(); + if matches!(status, Status::Success | Status::Fail) { + return Ok(JSValue::UNDEFINED); + } + + // A CancelRequest names the backend *process*, not a statement, so it + // stops whatever that backend is running: the request at the head of the + // connection's FIFO. Sending one for any other request would kill an + // unrelated query, so everything else is settled locally. + if status == Status::Pending || !connection.is_current_request(core::ptr::from_ref(this)) { + let err = postgres_error_to_js( + global_object, + Some(b"Query cancelled"), + AnyPostgresError::QueryCancelled, + ); + if status == Status::Pending { + // Nothing of this request is on the wire. Failing it keeps the + // backend from ever running it: advance() discards a Fail entry + // instead of writing its Bind/Execute. this.on_js_error(err, global_object); - Ok(JSValue::UNDEFINED) - } - Status::Binding | Status::Running | Status::PartialResponse => { - // Copy the key out before allocating into the JS heap, so no - // `JsCell` borrow is live across a call that can re-enter. - let (process_id, packet) = { - let key = connection.backend_key_data.get(); - (key.process_id, key.cancel_request()) - }; - // The server never sent BackendKeyData, so it cannot be asked to - // cancel anything. The query keeps running. - if process_id == 0 { - return Ok(JSValue::UNDEFINED); - } - Ok(crate::jsc::JSUint8Array::from_bytes_copy( - global_object, - &packet, - )) + } else { + // Pipelined onto the wire behind the head request, so the backend + // will run it regardless. Reject the promise but leave the entry + // in the FIFO to consume the answers that are already coming. + this.reject_in_place(err, global_object); } - Status::Success | Status::Fail => Ok(JSValue::UNDEFINED), + return Ok(JSValue::UNDEFINED); } + + // Copy the key out before allocating into the JS heap, so no `JsCell` + // borrow is live across a call that can re-enter. + let (process_id, packet) = { + let key = connection.backend_key_data.get(); + (key.process_id, key.cancel_request()) + }; + // The server never sent BackendKeyData, so it cannot be asked to cancel + // anything. The query keeps running. + if process_id == 0 { + return Ok(JSValue::UNDEFINED); + } + Ok(crate::jsc::JSUint8Array::from_bytes_copy( + global_object, + &packet, + )) } } diff --git a/test/js/sql/postgres-query-cancel.test.ts b/test/js/sql/postgres-query-cancel.test.ts index e7261e425689..d69df9fc7611 100644 --- a/test/js/sql/postgres-query-cancel.test.ts +++ b/test/js/sql/postgres-query-cancel.test.ts @@ -14,30 +14,61 @@ import net from "node:net"; import { pgAuthenticationOk, pgBackendKeyData, + pgBindComplete, pgCancelRequest, pgCommandComplete, pgDataRow, pgErrorResponse, + pgParameterDescription, + pgParseComplete, + pgReadFrontendMessages, pgReadyForQuery, pgRowDescription, } from "./wire-frames"; const PROCESS_ID = 4242; const SECRET_KEY = 13371337; +// text: its binary and text encodings are the same bytes, so the mock does not +// have to care whether Bun asked for binary results (it does for a statement it +// has already prepared). const TEXT_OID = 25; /** - * Completes the handshake (advertising BackendKeyData) and then leaves every - * query unanswered, the way a backend stuck inside pg_sleep() would. The test - * drives the reply itself. The connection a CancelRequest arrives on is always - * the second one, because the first is busy running the query. + * Scripted Postgres backend. + * + * While `autoReply` is on it answers each query unit with one text row, which is + * what drives a statement to the Prepared state. With it off, queries are left + * unanswered the way a backend stuck inside pg_sleep() would leave them, and the + * test writes every reply itself. A CancelRequest always arrives on the second + * connection, because the first one is busy running the query. */ -async function hangingBackend() { - const queryReceived = Promise.withResolvers(); +async function backend() { const cancelPacket = Promise.withResolvers(); const sockets = new Set(); + const waiters = new Map void>(); let queryConnection: net.Socket | undefined; let connections = 0; + let queryUnits = 0; + let autoReply = true; + + // Answer a Parse+Describe+Bind+Execute with one text row: ParseComplete and + // the two Describe replies, then the Execute replies. + const preparedReply = () => + Buffer.concat([ + pgParseComplete(), + pgParameterDescription([]), + pgRowDescription([{ name: "v", typeOid: TEXT_OID }]), + pgBindComplete(), + pgDataRow([Buffer.from("ok")]), + pgCommandComplete("SELECT 1"), + pgReadyForQuery(), + ]); + + function onQueryUnit() { + queryUnits++; + waiters.get(queryUnits)?.(); + if (autoReply) queryConnection!.write(preparedReply()); + } const server = net.createServer(socket => { sockets.add(socket); @@ -58,7 +89,8 @@ async function hangingBackend() { queryConnection = socket; let handshaken = false; - socket.on("data", () => { + let buffered = Buffer.alloc(0); + socket.on("data", data => { if (!handshaken) { handshaken = true; socket.write( @@ -66,7 +98,11 @@ async function hangingBackend() { ); return; } - queryReceived.resolve(); + buffered = pgReadFrontendMessages(Buffer.concat([buffered, data]), type => { + // Sync ends every extended-protocol unit; the simple protocol's Query is + // its own sync point. + if (type === "S" || type === "Q") onQueryUnit(); + }); }); }); await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); @@ -74,11 +110,31 @@ async function hangingBackend() { return { url: `postgres://postgres@127.0.0.1:${port}/postgres`, - queryReceived: queryReceived.promise, cancelPacket: cancelPacket.promise, get connections() { return connections; }, + set autoReply(value: boolean) { + autoReply = value; + }, + /** Resolves once the client has sent its `n`th complete query unit. */ + untilQueryUnits(n: number): Promise { + if (queryUnits >= n) return Promise.resolve(); + const { promise, resolve } = Promise.withResolvers(); + waiters.set(n, resolve); + return promise; + }, + /** Answer one Bind+Execute of a statement the backend already prepared. */ + answerPrepared(value: string) { + queryConnection!.write( + Buffer.concat([ + pgBindComplete(), + pgDataRow([Buffer.from(value)]), + pgCommandComplete("SELECT 1"), + pgReadyForQuery(), + ]), + ); + }, reply(...frames: Buffer[]) { queryConnection!.write(Buffer.concat(frames)); }, @@ -98,26 +154,27 @@ const protocols: [name: string, start: (query: any) => any][] = [ ]; test.each(protocols)("cancel() on a running %s query sends a CancelRequest", async (_name, start) => { - await using backend = await hangingBackend(); - await using sql = new SQL({ url: backend.url, max: 1, connectionTimeout: 5 }); + await using server = await backend(); + server.autoReply = false; + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); const query = start(sql`select pg_sleep(10)`); const settled = query.then( (rows: unknown) => rows, (err: any) => err, ); - await backend.queryReceived; + await server.untilQueryUnits(1); query.cancel(); // The CancelRequest names the backend by the pid/secret pair it handed out in // BackendKeyData, on a connection of its own. - expect(await backend.cancelPacket).toEqual(pgCancelRequest(PROCESS_ID, SECRET_KEY)); - expect(backend.connections).toBe(2); + expect(await server.cancelPacket).toEqual(pgCancelRequest(PROCESS_ID, SECRET_KEY)); + expect(server.connections).toBe(2); // A real backend answers the cancelled query on its own connection, with // SQLSTATE 57014 (query_canceled). - backend.reply( + server.reply( pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), pgReadyForQuery(), ); @@ -132,8 +189,8 @@ test.each(protocols)("cancel() on a running %s query sends a CancelRequest", asy }); test("cancel() before the query is dispatched rejects it instead of hanging", async () => { - await using backend = await hangingBackend(); - await using sql = new SQL({ url: backend.url, max: 1, connectionTimeout: 5 }); + await using server = await backend(); + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); // Tagged templates are lazy: nothing has been sent, and nothing ever will be, // so cancel() has to settle the promise itself. @@ -147,19 +204,20 @@ test("cancel() before the query is dispatched rejects it instead of hanging", as message: "Query cancelled", }); // Never even asked the pool for a connection. - expect(backend.connections).toBe(0); + expect(server.connections).toBe(0); }); test("cancel() on a queued query does not cancel the one the backend is running", async () => { - await using backend = await hangingBackend(); - await using sql = new SQL({ url: backend.url, max: 1, connectionTimeout: 5 }); + await using server = await backend(); + server.autoReply = false; + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); const running = sql`select 'kept'`.simple().execute(); const runningSettled = running.then( rows => rows, err => err, ); - await backend.queryReceived; + await server.untilQueryUnits(1); // Dispatched onto the same connection, but behind the running query: none of // its bytes are on the wire, so a CancelRequest would stop the wrong query. @@ -177,7 +235,7 @@ test("cancel() on a queued query does not cancel the one the backend is running" message: "Query cancelled", }); - backend.reply( + server.reply( pgRowDescription([{ name: "v", typeOid: TEXT_OID }]), pgDataRow([Buffer.from("kept")]), pgCommandComplete("SELECT 1"), @@ -186,5 +244,56 @@ test("cancel() on a queued query does not cancel the one the backend is running" expect(await runningSettled).toEqual([{ v: "kept" }]); // No second connection was opened, so nothing was cancelled on the server. - expect(backend.connections).toBe(1); + expect(server.connections).toBe(1); +}); + +// A CancelRequest names the backend process, not a statement. Once a statement is +// prepared, Bun pipelines the next query's Bind/Execute straight onto the wire +// behind the running one (do_run's Prepared arm writes when `can_pipeline()`), so +// the pipelined query's bytes are on the socket while the backend is still busy +// with the query ahead of it. Cancelling it on the server would kill that other +// query instead. +test("cancel() on a pipelined query does not cancel the one the backend is running", async () => { + await using server = await backend(); + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + + // Warm both statements so each reaches the Prepared state. + expect(await sql`select 'a'`).toEqual([{ v: "ok" }]); + expect(await sql`select 'b'`).toEqual([{ v: "ok" }]); + server.autoReply = false; + + // `running` is the head of the connection's FIFO and the query the backend is + // executing; `pipelined` goes onto the wire right behind it. + const running = sql`select 'a'`.execute(); + const pipelined = sql`select 'b'`.execute(); + const runningSettled = running.then( + rows => rows, + err => err, + ); + const pipelinedSettled = pipelined.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(4); + + pipelined.cancel(); + + const err = await pipelinedSettled; + expect({ name: err.name, code: err.code, message: err.message }).toEqual({ + name: "PostgresError", + code: "ERR_POSTGRES_QUERY_CANCELLED", + message: "Query cancelled", + }); + // No CancelRequest went out, so the running query was left alone. + expect(server.connections).toBe(1); + + server.answerPrepared("kept"); + expect(await runningSettled).toEqual([{ v: "kept" }]); + + // The pipelined query's Bind/Execute were already on the wire, so the backend + // answers it too. Those replies have to be consumed in order or the connection + // desyncs, which the next query proves it did not. + server.answerPrepared("drained"); + server.autoReply = true; + expect(await sql`select 'c'`).toEqual([{ v: "ok" }]); }); diff --git a/test/js/sql/wire-frames.ts b/test/js/sql/wire-frames.ts index 84e129700ace..737b36c2ee5d 100644 --- a/test/js/sql/wire-frames.ts +++ b/test/js/sql/wire-frames.ts @@ -150,6 +150,40 @@ export function pgCommandComplete(tag: string): Buffer { return pgRaw("C", Buffer.concat([Buffer.from(tag), Buffer.from([0])])); } +// PostgreSQL FE/BE protocol §55.7 ParseComplete: Byte1('1') Int32(4) +export function pgParseComplete(): Buffer { + return pgRaw("1", Buffer.alloc(0)); +} + +// PostgreSQL FE/BE protocol §55.7 BindComplete: Byte1('2') Int32(4) +export function pgBindComplete(): Buffer { + return pgRaw("2", Buffer.alloc(0)); +} + +// PostgreSQL FE/BE protocol §55.7 ParameterDescription: Byte1('t') Int32(len) Int16(nparams) Int32[nparams](typeOid) +export function pgParameterDescription(typeOids: number[]): Buffer { + const body = Buffer.alloc(2 + 4 * typeOids.length); + body.writeInt16BE(typeOids.length, 0); + for (let i = 0; i < typeOids.length; i++) body.writeInt32BE(typeOids[i], 2 + 4 * i); + return pgRaw("t", body); +} + +/** + * Drain complete frontend messages from `buffered`, calling onMessage(type, body) + * for each; returns the leftover bytes. Every frontend message after the startup + * packet is framed exactly like a backend one: Byte1(type) Int32(len including + * itself) body. + */ +export function pgReadFrontendMessages(buffered: Buffer, onMessage: (type: string, body: Buffer) => void): Buffer { + while (buffered.length >= 5) { + const len = buffered.readInt32BE(1); + if (len < 4 || buffered.length < 1 + len) break; + onMessage(String.fromCharCode(buffered[0]), buffered.subarray(5, 1 + len)); + buffered = buffered.subarray(1 + len); + } + return buffered; +} + export type PgRowDescriptionColumn = { name: string; tableOid?: number; From 771c0086d835d7f8308dde80fc6a16f1c2287a75 Mon Sep 17 00:00:00 2001 From: robobun Date: Sun, 5 Jul 2026 13:32:12 +0000 Subject: [PATCH 03/34] sql: release the postgres query's connection edge on the failure paths The `connection` cached value a query keeps so that cancel() can reach the connection it ran on is a strong GC edge. `allow_gc` clears it for a request that completed, but `on_js_error` and `on_write_fail` did not, so holding a settled Query kept its whole connection reachable: socket buffers, the prepared-statement map and all. Clear it on the failure paths too, through one helper shared with `allow_gc` so the next slot added here has an obvious place to be released. `do_cancel` reads the value before it hands off to `on_js_error`, so nothing loses its connection early. --- src/sql_jsc/postgres/PostgresSQLQuery.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/sql_jsc/postgres/PostgresSQLQuery.rs b/src/sql_jsc/postgres/PostgresSQLQuery.rs index 4b1f22c23233..4c8589f84527 100644 --- a/src/sql_jsc/postgres/PostgresSQLQuery.rs +++ b/src/sql_jsc/postgres/PostgresSQLQuery.rs @@ -201,6 +201,7 @@ impl PostgresSQLQuery { let Some(this_value) = self.this_value.get().try_get() else { return; }; + Self::release_connection(this_value, global_object); let _downgrade = scopeguard::guard((), |_| self.this_value.with_mut(|r| r.downgrade())); let Some(target_value) = self.get_target(global_object, true) else { return; @@ -228,6 +229,13 @@ impl PostgresSQLQuery { ); } + /// Drop the query's strong GC edge to the connection it ran on. Every + /// terminal path has to do this, or holding a settled `Query` keeps the whole + /// connection (socket buffers, prepared-statement map) reachable. + fn release_connection(this_value: JSValue, global_object: &JSGlobalObject) { + js::connection_set_cached(this_value, global_object, JSValue::ZERO); + } + pub fn on_js_error(&self, err: JSValue, global_object: &JSGlobalObject) { // R-2: see `on_write_fail` — `&self` + Cell/JsCell, ScopedRef brackets re-entry. let _deref = self.ref_guard(); @@ -235,6 +243,7 @@ impl PostgresSQLQuery { let Some(this_value) = self.this_value.get().try_get() else { return; }; + Self::release_connection(this_value, global_object); let _downgrade = scopeguard::guard((), |_| self.this_value.with_mut(|r| r.downgrade())); let Some(target_value) = self.get_target(global_object, true) else { return; @@ -306,7 +315,7 @@ impl PostgresSQLQuery { js::binding_set_cached(this_value, global_object, JSValue::ZERO); js::pending_value_set_cached(this_value, global_object, JSValue::ZERO); js::target_set_cached(this_value, global_object, JSValue::ZERO); - js::connection_set_cached(this_value, global_object, JSValue::ZERO); + Self::release_connection(this_value, global_object); } pub fn on_result( From 610937456cd533b9c486cc3f2a6e7310569405dd Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 6 Sep 2026 06:41:43 +0000 Subject: [PATCH 04/34] sql: reject a cancelled query when it first runs, not inside cancel() A query that is cancelled before it is dispatched now rejects from #run() and #runAsync(), the same placement as #41492. cancel() no longer rejects the promise itself. An eager reject inside cancel() makes a cancelled query that nobody awaits an unhandled rejection, which exits the process with code 1. Carry #41492's sqlite tests so the sqlite and mysql adapters are covered in this branch too. After #41492 merges, the query.ts hunks for #run() and #runAsync() resolve as identical on rebase. --- src/js/internal/sql/query.ts | 38 ++++++++-------- test/js/sql/postgres-query-cancel.test.ts | 2 +- test/js/sql/sqlite-sql.test.ts | 53 +++++++++++++++++++++++ 3 files changed, 73 insertions(+), 20 deletions(-) diff --git a/src/js/internal/sql/query.ts b/src/js/internal/sql/query.ts index 5993d157374d..4ba75f3d2eef 100644 --- a/src/js/internal/sql/query.ts +++ b/src/js/internal/sql/query.ts @@ -105,10 +105,7 @@ class Query> extends PublicPromise { #run() { const { [_handler]: handler, [_queryStatus]: status } = this; - if ( - status & - (SQLQueryStatus.executed | SQLQueryStatus.error | SQLQueryStatus.cancelled | SQLQueryStatus.invalidHandle) - ) { + if (status & (SQLQueryStatus.executed | SQLQueryStatus.error | SQLQueryStatus.invalidHandle)) { return; } @@ -117,6 +114,11 @@ class Query> extends PublicPromise { return; } + if (status & SQLQueryStatus.cancelled) { + this.reject(this[_adapter].queryCancelledError()); + return; + } + this[_queryStatus] |= SQLQueryStatus.executed; const handle = this.#getQueryHandle(); @@ -135,10 +137,7 @@ class Query> extends PublicPromise { async #runAsync() { const { [_handler]: handler, [_queryStatus]: status } = this; - if ( - status & - (SQLQueryStatus.executed | SQLQueryStatus.error | SQLQueryStatus.cancelled | SQLQueryStatus.invalidHandle) - ) { + if (status & (SQLQueryStatus.executed | SQLQueryStatus.error | SQLQueryStatus.invalidHandle)) { return; } @@ -147,6 +146,11 @@ class Query> extends PublicPromise { return; } + if (status & SQLQueryStatus.cancelled) { + this.reject(this[_adapter].queryCancelledError()); + return; + } + this[_queryStatus] |= SQLQueryStatus.executed; const handle = this.#getQueryHandle(); @@ -223,18 +227,14 @@ class Query> extends PublicPromise { this[_queryStatus] |= SQLQueryStatus.cancelled; - if (!(status & SQLQueryStatus.executed)) { - // Never dispatched, so no connection will ever settle this promise. - this.reject(this[_adapter].queryCancelledError()); - return this; - } - - const handle = this.#getQueryHandle(); + if (status & SQLQueryStatus.executed) { + const handle = this.#getQueryHandle(); - if (handle) { - const cancelRequest = handle.cancel?.(); - if (cancelRequest) { - this[_adapter].sendCancelRequest?.(cancelRequest); + if (handle) { + const cancelRequest = handle.cancel?.(); + if (cancelRequest) { + this[_adapter].sendCancelRequest?.(cancelRequest); + } } } diff --git a/test/js/sql/postgres-query-cancel.test.ts b/test/js/sql/postgres-query-cancel.test.ts index d69df9fc7611..bba8de7c8732 100644 --- a/test/js/sql/postgres-query-cancel.test.ts +++ b/test/js/sql/postgres-query-cancel.test.ts @@ -193,7 +193,7 @@ test("cancel() before the query is dispatched rejects it instead of hanging", as await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); // Tagged templates are lazy: nothing has been sent, and nothing ever will be, - // so cancel() has to settle the promise itself. + // so the first consumer of the promise has to reject it. const query = sql`select 1`; query.cancel(); diff --git a/test/js/sql/sqlite-sql.test.ts b/test/js/sql/sqlite-sql.test.ts index 540c78339e13..9106a994e49c 100644 --- a/test/js/sql/sqlite-sql.test.ts +++ b/test/js/sql/sqlite-sql.test.ts @@ -914,6 +914,59 @@ describe("Query Execution", () => { expect(result2).toHaveLength(1); expect(result2[0].id).toBe(2); }); + + // These tests `await` the cancelled query directly. A pending promise inside + // `expect().rejects` does not trip the test timeout, so a hang would stall the file. + function settle(promise: Promise) { + return promise.then( + () => "resolved", + (error: Error & { code?: string }) => ({ code: error.code, message: error.message }), + ); + } + + test("cancel() before the query runs rejects when awaited", async () => { + const query = sql`SELECT 1 AS x`; + query.cancel(); + expect(query.cancelled).toBe(true); + + expect(await settle(query)).toEqual({ code: "ERR_SQLITE_QUERY_CANCELLED", message: "Query cancelled" }); + // The connection stays usable. + expect(await sql`SELECT 2 AS x`).toEqual([{ x: 2 }]); + }); + + test("cancel() before the query runs settles a Promise.all batch", async () => { + const cancelled = sql`SELECT 1 AS x`; + cancelled.cancel(); + const live = sql`SELECT 2 AS x`; + + expect(await settle(Promise.all([cancelled, live]))).toEqual({ + code: "ERR_SQLITE_QUERY_CANCELLED", + message: "Query cancelled", + }); + expect(await live).toEqual([{ x: 2 }]); + }); + + test("cancel() before execute() rejects instead of running", async () => { + await sql`CREATE TABLE cancel_before_execute (id INTEGER)`; + const query = sql`INSERT INTO cancel_before_execute VALUES (1)`; + query.cancel(); + query.execute(); + + expect(await settle(query)).toEqual({ code: "ERR_SQLITE_QUERY_CANCELLED", message: "Query cancelled" }); + expect(await sql`SELECT count(*) AS n FROM cancel_before_execute`).toEqual([{ n: 0 }]); + }); + + // A query that never runs opens no connection, so the server does not need to exist. + test.each([ + ["postgres://u:p@127.0.0.1:9/db", "ERR_POSTGRES_QUERY_CANCELLED"], + ["mysql://u:p@127.0.0.1:9/db", "ERR_MYSQL_QUERY_CANCELLED"], + ])("cancel() before the query runs rejects for %s", async (url, code) => { + await using remote = new SQL(url); + const query = remote`SELECT 1 AS x`; + query.cancel(); + + expect(await settle(query)).toEqual({ code, message: "Query cancelled" }); + }); }); describe("Parameterized Queries", () => { From df87e6e5b65005159c33c398b2700c9e08ca6143 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 6 Sep 2026 06:51:38 +0000 Subject: [PATCH 05/34] sql: trim the comments on the postgres cancel path Keep the facts a reader cannot recover from the code alone (the cancel connection is plaintext on purpose, a CancelRequest targets the backend process rather than a statement, a pipelined request must keep its FIFO entry) and drop the rest. No code changes. --- src/js/internal/sql/postgres.ts | 19 +++----- src/js/internal/sql/query.ts | 6 +-- src/js/internal/sql/shared.ts | 6 +-- src/runtime/api/sql.classes.ts | 4 +- src/sql/postgres/protocol/BackendKeyData.rs | 8 ++-- src/sql_jsc/postgres/PostgresSQLConnection.rs | 5 +-- src/sql_jsc/postgres/PostgresSQLQuery.rs | 45 ++++++------------- 7 files changed, 26 insertions(+), 67 deletions(-) diff --git a/src/js/internal/sql/postgres.ts b/src/js/internal/sql/postgres.ts index aa1efa26e406..48b5c2b4260e 100644 --- a/src/js/internal/sql/postgres.ts +++ b/src/js/internal/sql/postgres.ts @@ -30,8 +30,6 @@ const { const cmds = ["", "INSERT", "DELETE", "UPDATE", "MERGE", "SELECT", "MOVE", "FETCH", "COPY"]; -// How long the connection opened for a CancelRequest waits for the backend to -// close it before giving up. const CANCEL_REQUEST_TIMEOUT_SECONDS = 5; const escapeBackslash = /\\/g; @@ -421,12 +419,9 @@ class PostgresAdapter } /** - * A backend running a query reads nothing until it finishes, so the only way - * to stop it is a CancelRequest on a second connection. The backend handles - * that message before authentication and before any SSL negotiation, and it - * carries no credentials beyond the pid/secret pair the server itself handed - * out in BackendKeyData, so the cancel connection stays plaintext, the way - * libpq's PQcancel() sends it. + * Plaintext on purpose: the backend handles CancelRequest before SSL + * negotiation, and the packet carries only the pid/secret the server itself + * issued. This matches libpq's PQcancel(). */ sendCancelRequest(request: Uint8Array): void { const { path, hostname, port } = this.connectionInfo; @@ -438,18 +433,14 @@ class PostgresAdapter open(socket) { socket.write(request); socket.flush(); - // The backend closes the connection once it has acted on the request. - // Bound the wait so a peer that never answers cannot pin the event loop. socket.timeout(CANCEL_REQUEST_TIMEOUT_SECONDS); }, timeout(socket) { socket.end(); }, - // The backend never replies to a CancelRequest, but Bun.connect requires - // a reader. + // Bun.connect requires a data handler; the backend never replies. data() {}, - // Cancelling is best effort: a request that never reaches the server - // just leaves the query running, which is what happens today anyway. + // Best effort: a cancel that never arrives leaves the query running. connectError() {}, error() {}, }, diff --git a/src/js/internal/sql/query.ts b/src/js/internal/sql/query.ts index 4ba75f3d2eef..e747efb3c3c4 100644 --- a/src/js/internal/sql/query.ts +++ b/src/js/internal/sql/query.ts @@ -15,11 +15,7 @@ const PublicPromise = Promise; export interface BaseQueryHandle { done?(): void; - /** - * Abort a query the handle already dispatched. Returns the request bytes the - * adapter has to deliver out-of-band (Postgres sends a CancelRequest on a - * second connection), or undefined when nothing has to reach the server. - */ + /** Returns bytes the adapter must deliver out-of-band, or undefined. */ cancel?(): Uint8Array | undefined; setMode(mode: SQLQueryResultMode): void; run(connection: Connection, query: Query): void | Promise; diff --git a/src/js/internal/sql/shared.ts b/src/js/internal/sql/shared.ts index 1e2302961c7a..52f588785e42 100644 --- a/src/js/internal/sql/shared.ts +++ b/src/js/internal/sql/shared.ts @@ -2141,11 +2141,7 @@ export interface DatabaseAdapter { queryCancelledError(): Error; invalidTransactionStateError(message: string): Error; - /** - * Deliver a `Query.cancel()` request that cannot travel on the query's own - * connection, because that connection is busy running the query being - * cancelled. Postgres opens a second connection to the same server for it. - */ + /** Deliver the bytes `QueryHandle.cancel()` returned on a separate connection. */ sendCancelRequest?(request: Uint8Array): void; } diff --git a/src/runtime/api/sql.classes.ts b/src/runtime/api/sql.classes.ts index c3ea03fdd5b0..d805207c9015 100644 --- a/src/runtime/api/sql.classes.ts +++ b/src/runtime/api/sql.classes.ts @@ -92,9 +92,7 @@ for (const type of types) { length: 1, }, }, - // Postgres cancels a running query by sending a CancelRequest on a - // second connection, so its query handle has to remember which - // connection it was dispatched to. + // `connection` lets a Postgres query find its BackendKeyData for cancel(). values: type === "PostgresSQL" ? ["pendingValue", "target", "columns", "binding", "connection"] diff --git a/src/sql/postgres/protocol/BackendKeyData.rs b/src/sql/postgres/protocol/BackendKeyData.rs index a5d2c9b954e1..ad15e10268d1 100644 --- a/src/sql/postgres/protocol/BackendKeyData.rs +++ b/src/sql/postgres/protocol/BackendKeyData.rs @@ -1,8 +1,7 @@ use super::new_reader::NewReader; use crate::postgres::AnyPostgresError; -/// Protocol §55.2.3: the request code a CancelRequest carries in place of the -/// protocol version, `(1234 << 16) | 5678`. +/// CancelRequest's stand-in for the protocol version: `(1234 << 16) | 5678`. const CANCEL_REQUEST_CODE: u32 = 80877102; #[derive(Default)] @@ -18,9 +17,8 @@ impl BackendKeyData { Self::decode_internal(NewReader { wrapped: context }) } - /// Protocol §55.2.3 CancelRequest: `Int32(16) Int32(80877102) Int32(pid) Int32(secret)`. - /// It has no message-type byte because it is only ever sent as the first - /// message of a *separate* connection, which the backend then closes. + /// `Int32(16) Int32(80877102) Int32(pid) Int32(secret)`: no type byte, it + /// is the only message on a connection opened just to carry it. pub fn cancel_request(&self) -> [u8; 16] { let mut packet = [0u8; 16]; packet[0..4].copy_from_slice(&16u32.to_be_bytes()); diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index 9026616f4f47..eeb868ff8f50 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -1572,10 +1572,7 @@ impl PostgresSQLConnection { )) } - /// True when `request` is the head of the FIFO, i.e. the one the backend is - /// executing right now. Requests behind the head have either not been - /// written at all, or were pipelined onto the wire and the backend has not - /// reached them yet. + /// Whether `request` is the FIFO head, the one the backend is executing now. pub fn is_current_request(&self, request: *const PostgresSQLQuery) -> bool { let q = self.requests.get(); q.readable_length() > 0 && core::ptr::eq(q.peek_item(0).cast_const(), request) diff --git a/src/sql_jsc/postgres/PostgresSQLQuery.rs b/src/sql_jsc/postgres/PostgresSQLQuery.rs index 4c8589f84527..ad8c03ec0c7a 100644 --- a/src/sql_jsc/postgres/PostgresSQLQuery.rs +++ b/src/sql_jsc/postgres/PostgresSQLQuery.rs @@ -229,9 +229,8 @@ impl PostgresSQLQuery { ); } - /// Drop the query's strong GC edge to the connection it ran on. Every - /// terminal path has to do this, or holding a settled `Query` keeps the whole - /// connection (socket buffers, prepared-statement map) reachable. + /// The cached `connection` is a strong GC edge; every terminal path must + /// clear it or a retained `Query` pins the whole connection. fn release_connection(this_value: JSValue, global_object: &JSGlobalObject) { js::connection_set_cached(this_value, global_object, JSValue::ZERO); } @@ -251,15 +250,10 @@ impl PostgresSQLQuery { self.run_reject_callback(global_object, this_value, target_value, err); } - /// Reject the promise of a request whose Bind/Execute is already on the wire. - /// - /// Unlike [`on_js_error`](Self::on_js_error) this leaves `status`, `target` - /// and the strong `this_value` alone: the backend is going to answer this - /// request no matter what, and the connection has to keep the FIFO entry to - /// consume those answers in order. `Status::Fail` would make `advance()` - /// discard the entry and the next BindComplete would land on the wrong - /// request. The request then finishes down the normal path, where - /// `Query.resolve()` on an already rejected promise is a no-op. + /// Reject a request whose Bind/Execute is already on the wire. Unlike + /// `on_js_error` this leaves `status` and the FIFO entry alone: the backend + /// will still answer, and a `Fail` entry gets discarded by `advance()`, so + /// the next BindComplete would land on the wrong request. pub fn reject_in_place(&self, err: JSValue, global_object: &JSGlobalObject) { let _deref = self.ref_guard(); let Some(this_value) = self.this_value.get().try_get() else { @@ -890,17 +884,14 @@ impl PostgresSQLQuery { Ok(JSValue::UNDEFINED) } - /// Returns the CancelRequest packet the caller must deliver on a second - /// connection, or `undefined` when there is nothing for the server to stop. + /// Returns the CancelRequest packet to deliver on a second connection, or + /// `undefined` when there is nothing for the server to stop. pub fn do_cancel( this: &Self, global_object: &JSGlobalObject, callframe: &CallFrame, ) -> JsResult { let this_value = callframe.this(); - // No connection cached means `run()` never bound this query to one, so - // the pool still owes it a connection (or it already finished). Either - // way there is nothing on the wire to cancel. let Some(connection_value) = js::connection_get_cached(this_value) else { return Ok(JSValue::UNDEFINED); }; @@ -913,10 +904,8 @@ impl PostgresSQLQuery { return Ok(JSValue::UNDEFINED); } - // A CancelRequest names the backend *process*, not a statement, so it - // stops whatever that backend is running: the request at the head of the - // connection's FIFO. Sending one for any other request would kill an - // unrelated query, so everything else is settled locally. + // A CancelRequest names the backend process, not a statement, so it only + // ever stops the FIFO head. Anything else is settled locally. if status == Status::Pending || !connection.is_current_request(core::ptr::from_ref(this)) { let err = postgres_error_to_js( global_object, @@ -924,27 +913,21 @@ impl PostgresSQLQuery { AnyPostgresError::QueryCancelled, ); if status == Status::Pending { - // Nothing of this request is on the wire. Failing it keeps the - // backend from ever running it: advance() discards a Fail entry - // instead of writing its Bind/Execute. + // Nothing on the wire yet: a Fail entry is discarded, never written. this.on_js_error(err, global_object); } else { - // Pipelined onto the wire behind the head request, so the backend - // will run it regardless. Reject the promise but leave the entry - // in the FIFO to consume the answers that are already coming. + // Already on the wire: the backend will answer it regardless. this.reject_in_place(err, global_object); } return Ok(JSValue::UNDEFINED); } - // Copy the key out before allocating into the JS heap, so no `JsCell` - // borrow is live across a call that can re-enter. + // Copy out before the JS-heap allocation below can re-enter. let (process_id, packet) = { let key = connection.backend_key_data.get(); (key.process_id, key.cancel_request()) }; - // The server never sent BackendKeyData, so it cannot be asked to cancel - // anything. The query keeps running. + // No BackendKeyData was ever received, so the server cannot be asked. if process_id == 0 { return Ok(JSValue::UNDEFINED); } From 43d3780f6801d78bdaf1183a9951ed6534684072 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 6 Sep 2026 07:12:25 +0000 Subject: [PATCH 06/34] sql: bound the postgres cancel connection's connect attempt too The CancelRequest socket armed its timeout inside Bun.connect's open handler, which only runs once the TCP handshake completes. A peer that drops SYNs (host gone, firewall, draining load balancer) left the attempt pending for the OS connect timeout, about two minutes on Linux, and that pinned the event loop for the whole time. Use net.connect, which hands back the socket before the handshake, so setTimeout covers the connect phase as well. The write moves into the connect handler: a write queued before connect counts as pending data, and net.Socket suppresses its timeout while any is outstanding. Verified against a loopback SYN sink (a listener whose accept queue is full drops further SYNs): the previous placement stayed pending past 8 seconds, the new one times out and destroys the socket at the configured bound. --- src/js/internal/sql/postgres.ts | 34 +++++++++++++-------------------- 1 file changed, 13 insertions(+), 21 deletions(-) diff --git a/src/js/internal/sql/postgres.ts b/src/js/internal/sql/postgres.ts index 48b5c2b4260e..cc2d85197681 100644 --- a/src/js/internal/sql/postgres.ts +++ b/src/js/internal/sql/postgres.ts @@ -30,7 +30,7 @@ const { const cmds = ["", "INSERT", "DELETE", "UPDATE", "MERGE", "SELECT", "MOVE", "FETCH", "COPY"]; -const CANCEL_REQUEST_TIMEOUT_SECONDS = 5; +const CANCEL_REQUEST_TIMEOUT_MS = 5_000; const escapeBackslash = /\\/g; const escapeQuote = /"/g; @@ -425,26 +425,18 @@ class PostgresAdapter */ sendCancelRequest(request: Uint8Array): void { const { path, hostname, port } = this.connectionInfo; - const address = path ? { unix: path } : { hostname, port }; - - Bun.connect({ - ...address, - socket: { - open(socket) { - socket.write(request); - socket.flush(); - socket.timeout(CANCEL_REQUEST_TIMEOUT_SECONDS); - }, - timeout(socket) { - socket.end(); - }, - // Bun.connect requires a data handler; the backend never replies. - data() {}, - // Best effort: a cancel that never arrives leaves the query running. - connectError() {}, - error() {}, - }, - }); + const net = require("node:net"); + + // net.connect hands back the socket before the handshake completes, so + // the timeout also bounds a connect attempt that never gets a SYN-ACK. + const socket = net.connect(path ? { path } : { host: hostname, port }); + socket.setTimeout(CANCEL_REQUEST_TIMEOUT_MS); + socket.on("timeout", () => socket.destroy()); + // Best effort: a cancel that never arrives leaves the query running. + socket.on("error", () => {}); + // Write only once connected: a write queued before that counts as pending + // data and net.Socket suppresses its timeout while any is outstanding. + socket.on("connect", () => socket.end(request)); } connectionClosedError() { From afef5ca52055405f2e607aa35105ac5a428b3dc8 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 6 Sep 2026 07:14:51 +0000 Subject: [PATCH 07/34] sql: one-line the two comments on the postgres cancel socket --- src/js/internal/sql/postgres.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/js/internal/sql/postgres.ts b/src/js/internal/sql/postgres.ts index cc2d85197681..a2b3b9927310 100644 --- a/src/js/internal/sql/postgres.ts +++ b/src/js/internal/sql/postgres.ts @@ -427,15 +427,13 @@ class PostgresAdapter const { path, hostname, port } = this.connectionInfo; const net = require("node:net"); - // net.connect hands back the socket before the handshake completes, so - // the timeout also bounds a connect attempt that never gets a SYN-ACK. + // net.connect returns before the handshake, so the timeout covers it too. const socket = net.connect(path ? { path } : { host: hostname, port }); socket.setTimeout(CANCEL_REQUEST_TIMEOUT_MS); socket.on("timeout", () => socket.destroy()); // Best effort: a cancel that never arrives leaves the query running. socket.on("error", () => {}); - // Write only once connected: a write queued before that counts as pending - // data and net.Socket suppresses its timeout while any is outstanding. + // A write queued before connect suppresses net.Socket's timeout; write after. socket.on("connect", () => socket.end(request)); } From f119b73b8925330a125ba27ae24355717f15e33e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 6 Sep 2026 07:43:51 +0000 Subject: [PATCH 08/34] sql: move the cancel-before-run tests into their own file The sqlite/mysql "cancel() before the query runs" tests were carried into sqlite-sql.test.ts, a 240-test file with two fuzz tests that blow the per-test timeout under a debug+ASAN build regardless of this change. Moving the cancel tests to sql-query-cancel-before-run.test.ts keeps the coverage and takes the unrelated file out of this diff. sqlite-sql.test.ts is byte-identical to the merge base again. --- .../sql/sql-query-cancel-before-run.test.ts | 66 +++++++++++++++++++ test/js/sql/sqlite-sql.test.ts | 53 --------------- 2 files changed, 66 insertions(+), 53 deletions(-) create mode 100644 test/js/sql/sql-query-cancel-before-run.test.ts diff --git a/test/js/sql/sql-query-cancel-before-run.test.ts b/test/js/sql/sql-query-cancel-before-run.test.ts new file mode 100644 index 000000000000..3b1bd7460c7a --- /dev/null +++ b/test/js/sql/sql-query-cancel-before-run.test.ts @@ -0,0 +1,66 @@ +// Query.cancel() on a query that has not run yet must settle the promise once +// something consumes it. The rejection is deliberately not issued inside +// cancel() itself: a cancelled query nobody awaits would then be an unhandled +// rejection and exit the process with code 1. This is the shared query.ts path, +// so it is exercised on every adapter; a query that never runs opens no +// connection, so postgres and mysql need no server here. +import { SQL } from "bun"; +import { describe, expect, test } from "bun:test"; + +// These tests `await` the cancelled query directly. A pending promise inside +// `expect().rejects` does not trip the test timeout, so a hang would stall the file. +function settle(promise: Promise) { + return promise.then( + () => "resolved", + (error: Error & { code?: string }) => ({ code: error.code, message: error.message }), + ); +} + +describe("sqlite", () => { + test("cancel() before the query runs rejects when awaited", async () => { + await using sql = new SQL("sqlite://:memory:"); + const query = sql`SELECT 1 AS x`; + query.cancel(); + expect(query.cancelled).toBe(true); + + expect(await settle(query)).toEqual({ code: "ERR_SQLITE_QUERY_CANCELLED", message: "Query cancelled" }); + // The connection stays usable. + expect(await sql`SELECT 2 AS x`).toEqual([{ x: 2 }]); + }); + + test("cancel() before the query runs settles a Promise.all batch", async () => { + await using sql = new SQL("sqlite://:memory:"); + const cancelled = sql`SELECT 1 AS x`; + cancelled.cancel(); + const live = sql`SELECT 2 AS x`; + + expect(await settle(Promise.all([cancelled, live]))).toEqual({ + code: "ERR_SQLITE_QUERY_CANCELLED", + message: "Query cancelled", + }); + expect(await live).toEqual([{ x: 2 }]); + }); + + test("cancel() before execute() rejects instead of running", async () => { + await using sql = new SQL("sqlite://:memory:"); + await sql`CREATE TABLE cancel_before_execute (id INTEGER)`; + const query = sql`INSERT INTO cancel_before_execute VALUES (1)`; + query.cancel(); + query.execute(); + + expect(await settle(query)).toEqual({ code: "ERR_SQLITE_QUERY_CANCELLED", message: "Query cancelled" }); + expect(await sql`SELECT count(*) AS n FROM cancel_before_execute`).toEqual([{ n: 0 }]); + }); +}); + +// A query that never runs opens no connection, so the server does not need to exist. +test.each([ + ["postgres://u:p@127.0.0.1:9/db", "ERR_POSTGRES_QUERY_CANCELLED"], + ["mysql://u:p@127.0.0.1:9/db", "ERR_MYSQL_QUERY_CANCELLED"], +])("cancel() before the query runs rejects for %s", async (url, code) => { + await using remote = new SQL(url); + const query = remote`SELECT 1 AS x`; + query.cancel(); + + expect(await settle(query)).toEqual({ code, message: "Query cancelled" }); +}); diff --git a/test/js/sql/sqlite-sql.test.ts b/test/js/sql/sqlite-sql.test.ts index 9106a994e49c..540c78339e13 100644 --- a/test/js/sql/sqlite-sql.test.ts +++ b/test/js/sql/sqlite-sql.test.ts @@ -914,59 +914,6 @@ describe("Query Execution", () => { expect(result2).toHaveLength(1); expect(result2[0].id).toBe(2); }); - - // These tests `await` the cancelled query directly. A pending promise inside - // `expect().rejects` does not trip the test timeout, so a hang would stall the file. - function settle(promise: Promise) { - return promise.then( - () => "resolved", - (error: Error & { code?: string }) => ({ code: error.code, message: error.message }), - ); - } - - test("cancel() before the query runs rejects when awaited", async () => { - const query = sql`SELECT 1 AS x`; - query.cancel(); - expect(query.cancelled).toBe(true); - - expect(await settle(query)).toEqual({ code: "ERR_SQLITE_QUERY_CANCELLED", message: "Query cancelled" }); - // The connection stays usable. - expect(await sql`SELECT 2 AS x`).toEqual([{ x: 2 }]); - }); - - test("cancel() before the query runs settles a Promise.all batch", async () => { - const cancelled = sql`SELECT 1 AS x`; - cancelled.cancel(); - const live = sql`SELECT 2 AS x`; - - expect(await settle(Promise.all([cancelled, live]))).toEqual({ - code: "ERR_SQLITE_QUERY_CANCELLED", - message: "Query cancelled", - }); - expect(await live).toEqual([{ x: 2 }]); - }); - - test("cancel() before execute() rejects instead of running", async () => { - await sql`CREATE TABLE cancel_before_execute (id INTEGER)`; - const query = sql`INSERT INTO cancel_before_execute VALUES (1)`; - query.cancel(); - query.execute(); - - expect(await settle(query)).toEqual({ code: "ERR_SQLITE_QUERY_CANCELLED", message: "Query cancelled" }); - expect(await sql`SELECT count(*) AS n FROM cancel_before_execute`).toEqual([{ n: 0 }]); - }); - - // A query that never runs opens no connection, so the server does not need to exist. - test.each([ - ["postgres://u:p@127.0.0.1:9/db", "ERR_POSTGRES_QUERY_CANCELLED"], - ["mysql://u:p@127.0.0.1:9/db", "ERR_MYSQL_QUERY_CANCELLED"], - ])("cancel() before the query runs rejects for %s", async (url, code) => { - await using remote = new SQL(url); - const query = remote`SELECT 1 AS x`; - query.cancel(); - - expect(await settle(query)).toEqual({ code, message: "Query cancelled" }); - }); }); describe("Parameterized Queries", () => { From 7a18dc7b24264d41b65d161d2962e97f0ec0fba4 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 6 Sep 2026 11:53:04 +0000 Subject: [PATCH 09/34] ci: retrigger From 4f1d494f3d62a9a4863a6f6d95709389a39828f7 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sun, 6 Sep 2026 18:19:51 +0000 Subject: [PATCH 10/34] sql: release the pending-request count when a queued query is cancelled A queued query counts toward the connection's pending_requests until its bytes are written. Cancelling it before that point marked it Fail and let advance() discard it, but nothing took it out of the count, so the enqueue-time pipelining fast path stayed disabled for the rest of the connection's life. Route the cancel through finish_request first. --- src/sql_jsc/postgres/PostgresSQLConnection.rs | 4 +- src/sql_jsc/postgres/PostgresSQLQuery.rs | 1 + test/js/sql/postgres-query-cancel.test.ts | 39 +++++++++++++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index 29f9f81c3813..667d6fcfc810 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -1747,7 +1747,9 @@ impl PostgresSQLConnection { } } - fn finish_request(&self, item: &PostgresSQLQuery) { + /// Take `item` out of the connection's request accounting. Call it once, + /// while `item` still has the status it was counted under. + pub(crate) fn finish_request(&self, item: &PostgresSQLQuery) { match item.status.get() { QueryStatus::Running | QueryStatus::Binding | QueryStatus::PartialResponse => { let counter = item.flags.get().counter; diff --git a/src/sql_jsc/postgres/PostgresSQLQuery.rs b/src/sql_jsc/postgres/PostgresSQLQuery.rs index 1a1cb666696d..1e3f17f553da 100644 --- a/src/sql_jsc/postgres/PostgresSQLQuery.rs +++ b/src/sql_jsc/postgres/PostgresSQLQuery.rs @@ -867,6 +867,7 @@ impl PostgresSQLQuery { ); if status == Status::Pending { // Nothing on the wire yet: a Fail entry is discarded, never written. + connection.finish_request(this); this.on_js_error(err, global_object); } else { // Already on the wire: the backend will answer it regardless. diff --git a/test/js/sql/postgres-query-cancel.test.ts b/test/js/sql/postgres-query-cancel.test.ts index a120e6bae864..81c853a72e85 100644 --- a/test/js/sql/postgres-query-cancel.test.ts +++ b/test/js/sql/postgres-query-cancel.test.ts @@ -248,6 +248,45 @@ test("cancel() on a queued query does not cancel the one the backend is running" expect(server.connections).toBe(1); }); +// The connection counts queued requests whose bytes are not written yet, and only +// pipelines a prepared query at enqueue time while that count is zero. A queued +// query that is cancelled leaves the queue without ever being written, so it has +// to leave that count too, or the connection stops pipelining for good. +test("a connection still pipelines after a queued query on it was cancelled", async () => { + await using server = await backend(); + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + + // Warm the statement so each later run of it is a bare Bind/Execute. + expect(await sql`select 'p'`).toEqual([{ v: "ok" }]); + server.autoReply = false; + + const running = sql`select 'kept'`.simple().execute(); + await server.untilQueryUnits(2); + const queued = sql`select 'cancelled'`.simple().execute(); + const queuedSettled = queued.then( + rows => rows, + err => err, + ); + queued.cancel(); + expect((await queuedSettled).code).toBe("ERR_POSTGRES_QUERY_CANCELLED"); + server.reply( + pgRowDescription([{ name: "v", typeOid: TEXT_OID }]), + pgDataRow([Buffer.from("kept")]), + pgCommandComplete("SELECT 1"), + pgReadyForQuery(), + ); + expect(await running).toEqual([{ v: "kept" }]); + + // Both Bind/Execute units must reach the backend before it answers either: + // the second one rides the wire behind the first instead of waiting for it. + const first = sql`select 'p'`.execute(); + const second = sql`select 'p'`.execute(); + await server.untilQueryUnits(4); + server.answerPrepared("first"); + server.answerPrepared("second"); + expect(await Promise.all([first, second])).toEqual([[{ v: "first" }], [{ v: "second" }]]); +}); + // A CancelRequest names the backend process, not a statement. Once a statement is // prepared, Bun pipelines the next query's Bind/Execute straight onto the wire // behind the running one (do_run's Prepared arm writes when `can_pipeline()`), so From 907bd970193e395898100378368add4c8363ae48 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 24 Sep 2026 14:14:12 +0000 Subject: [PATCH 11/34] sql: reject a cancelled pipelined query through the in-flight rejection main now has one way to reject a request whose response is still coming: the discard_response flag, which skips that response until ReadyForQuery. The pipelined cancel needs exactly that, so it uses it in place of its own reject_in_place, and on_undecodable_row becomes reject_in_flight because it now serves both callers. --- src/sql_jsc/postgres/PostgresSQLConnection.rs | 4 +-- src/sql_jsc/postgres/PostgresSQLQuery.rs | 31 +++---------------- 2 files changed, 6 insertions(+), 29 deletions(-) diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index 1bf05b968b26..ee9bfc5b0419 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -2455,7 +2455,7 @@ impl PostgresSQLConnection { return Err(err); } let js_err = self.undecodable_row_error(err)?; - request.on_undecodable_row(js_err, self.global()); + request.reject_in_flight(js_err, self.global()); return Ok(()); } @@ -2479,7 +2479,7 @@ impl PostgresSQLConnection { Ok(result) => result, Err(err) => { let js_err = self.undecodable_row_error(err)?; - request.on_undecodable_row(js_err, self.global()); + request.reject_in_flight(js_err, self.global()); return Ok(()); } }; diff --git a/src/sql_jsc/postgres/PostgresSQLQuery.rs b/src/sql_jsc/postgres/PostgresSQLQuery.rs index a9867d2b1461..75c690f97d8a 100644 --- a/src/sql_jsc/postgres/PostgresSQLQuery.rs +++ b/src/sql_jsc/postgres/PostgresSQLQuery.rs @@ -77,7 +77,8 @@ pub struct Flags { pub(crate) binary: bool, pub(crate) bigint: bool, pub(crate) simple: bool, - /// Rejected for an undecodable row: in flight, its response skipped, until `ReadyForQuery`. + /// Rejected while in flight (an undecodable row, a cancel behind the FIFO head): its + /// response is skipped until `ReadyForQuery`. pub(crate) discard_response: bool, /// Which connection counter this request's dispatch incremented; reset to /// `None` when `finish_request` consumes that contribution, so the @@ -231,7 +232,7 @@ impl PostgresSQLQuery { } /// Rejects now, but `status` stays in flight: the server is still answering this query. - pub(crate) fn on_undecodable_row(&self, err: JSValue, global_object: &JSGlobalObject) { + pub(crate) fn reject_in_flight(&self, err: JSValue, global_object: &JSGlobalObject) { self.update_flags(|f| f.discard_response = true); self.reject(err, global_object); } @@ -251,31 +252,7 @@ impl PostgresSQLQuery { let Some(target_value) = self.get_target(global_object, true) else { return; }; - self.run_reject_callback(global_object, this_value, target_value, err); - } - - /// Reject a request whose Bind/Execute is already on the wire. Unlike - /// `on_js_error` this leaves `status` and the FIFO entry alone: the backend - /// will still answer, and a `Fail` entry gets discarded by `advance()`, so - /// the next BindComplete would land on the wrong request. - pub(crate) fn reject_in_place(&self, err: JSValue, global_object: &JSGlobalObject) { - let _guard = self.ref_guard(); - let Some(this_value) = self.this_value.get().try_get() else { - return; - }; - let Some(target_value) = self.get_target(global_object, false) else { - return; - }; - self.run_reject_callback(global_object, this_value, target_value, err); - } - fn run_reject_callback( - &self, - global_object: &JSGlobalObject, - this_value: JSValue, - target_value: JSValue, - err: JSValue, - ) { // SAFETY: JS-thread only; short-lived `&mut` to the singleton VM, no other live borrow. let vm = crate::jsc::VirtualMachine::get().as_mut(); let function = vm @@ -904,7 +881,7 @@ impl PostgresSQLQuery { this.on_js_error(err, global_object); } else { // Already on the wire: the backend will answer it regardless. - this.reject_in_place(err, global_object); + this.reject_in_flight(err, global_object); } return Ok(JSValue::UNDEFINED); } From 60a71dfd097730f1fc124f3e726c77aa61eed77f Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 24 Sep 2026 14:14:23 +0000 Subject: [PATCH 12/34] sql: let the query handler reject a query cancelled before it runs The explicit reject in #run() and #runAsync() returned before the query reached its handler. For a query on a reserved connection or in a transaction, that handler is what removes the query from the scope set, so the rejected query stayed in it: close({ timeout }) ended its wait at once with an unhandled rejection and never closed the connection. Dropping the cancelled bit from the two guards is enough. The handlers in sql.ts already reject a cancelled query, after they remove it from the set. The cancel-before-run tests for every adapter belong to the change that owns this fix, so the copy of them here goes away. This file keeps the postgres cases. --- src/js/internal/sql/query.ts | 10 --- test/js/sql/postgres-query-cancel.test.ts | 24 +++++++ .../sql/sql-query-cancel-before-run.test.ts | 66 ------------------- 3 files changed, 24 insertions(+), 76 deletions(-) delete mode 100644 test/js/sql/sql-query-cancel-before-run.test.ts diff --git a/src/js/internal/sql/query.ts b/src/js/internal/sql/query.ts index e5f6957b9aef..6a522b4e4ce8 100644 --- a/src/js/internal/sql/query.ts +++ b/src/js/internal/sql/query.ts @@ -111,11 +111,6 @@ class Query> extends PublicPromise { return; } - if (status & SQLQueryStatus.cancelled) { - this.reject(this[_adapter].queryCancelledError()); - return; - } - this[_queryStatus] |= SQLQueryStatus.executed; const handle = this.#getQueryHandle(); @@ -143,11 +138,6 @@ class Query> extends PublicPromise { return; } - if (status & SQLQueryStatus.cancelled) { - this.reject(this[_adapter].queryCancelledError()); - return; - } - this[_queryStatus] |= SQLQueryStatus.executed; const handle = this.#getQueryHandle(); diff --git a/test/js/sql/postgres-query-cancel.test.ts b/test/js/sql/postgres-query-cancel.test.ts index 81c853a72e85..faec79f9d5ae 100644 --- a/test/js/sql/postgres-query-cancel.test.ts +++ b/test/js/sql/postgres-query-cancel.test.ts @@ -44,6 +44,7 @@ const TEXT_OID = 25; */ async function backend() { const cancelPacket = Promise.withResolvers(); + const queryConnectionClosed = Promise.withResolvers(); const sockets = new Set(); const waiters = new Map void>(); let queryConnection: net.Socket | undefined; @@ -88,6 +89,7 @@ async function backend() { } queryConnection = socket; + socket.on("close", () => queryConnectionClosed.resolve()); let handshaken = false; let buffered = Buffer.alloc(0); socket.on("data", data => { @@ -112,6 +114,8 @@ async function backend() { return { url: `postgres://postgres@127.0.0.1:${port}/postgres`, cancelPacket: cancelPacket.promise, + /** Resolves once the client has closed the connection its queries run on. */ + queryConnectionClosed: queryConnectionClosed.promise, get connections() { return connections; }, @@ -287,6 +291,26 @@ test("a connection still pipelines after a queued query on it was cancelled", as expect(await Promise.all([first, second])).toEqual([[{ v: "first" }], [{ v: "second" }]]); }); +// A reserved connection keeps its queries in a scope set, and close({ timeout }) +// waits on that set. Only the query's own handler takes a cancelled query back out +// of it. A rejected query left in the set ends the wait at once, before the +// connection is closed, and the pool never gets the connection back. +test("a query cancelled before it runs leaves the scope of its reserved connection", async () => { + await using server = await backend(); + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + + const reserved = await sql.reserve(); + const query = reserved`select 1`; + query.cancel(); + const err = await query.catch((e: any) => e); + expect(err.code).toBe("ERR_POSTGRES_QUERY_CANCELLED"); + + await reserved.close({ timeout: 1 }); + await server.queryConnectionClosed; + // Nothing was ever sent for the cancelled query, so there was nothing to cancel. + expect(server.connections).toBe(1); +}); + // A CancelRequest names the backend process, not a statement. Once a statement is // prepared, Bun pipelines the next query's Bind/Execute straight onto the wire // behind the running one (do_run's Prepared arm writes when `can_pipeline()`), so diff --git a/test/js/sql/sql-query-cancel-before-run.test.ts b/test/js/sql/sql-query-cancel-before-run.test.ts deleted file mode 100644 index 3b1bd7460c7a..000000000000 --- a/test/js/sql/sql-query-cancel-before-run.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -// Query.cancel() on a query that has not run yet must settle the promise once -// something consumes it. The rejection is deliberately not issued inside -// cancel() itself: a cancelled query nobody awaits would then be an unhandled -// rejection and exit the process with code 1. This is the shared query.ts path, -// so it is exercised on every adapter; a query that never runs opens no -// connection, so postgres and mysql need no server here. -import { SQL } from "bun"; -import { describe, expect, test } from "bun:test"; - -// These tests `await` the cancelled query directly. A pending promise inside -// `expect().rejects` does not trip the test timeout, so a hang would stall the file. -function settle(promise: Promise) { - return promise.then( - () => "resolved", - (error: Error & { code?: string }) => ({ code: error.code, message: error.message }), - ); -} - -describe("sqlite", () => { - test("cancel() before the query runs rejects when awaited", async () => { - await using sql = new SQL("sqlite://:memory:"); - const query = sql`SELECT 1 AS x`; - query.cancel(); - expect(query.cancelled).toBe(true); - - expect(await settle(query)).toEqual({ code: "ERR_SQLITE_QUERY_CANCELLED", message: "Query cancelled" }); - // The connection stays usable. - expect(await sql`SELECT 2 AS x`).toEqual([{ x: 2 }]); - }); - - test("cancel() before the query runs settles a Promise.all batch", async () => { - await using sql = new SQL("sqlite://:memory:"); - const cancelled = sql`SELECT 1 AS x`; - cancelled.cancel(); - const live = sql`SELECT 2 AS x`; - - expect(await settle(Promise.all([cancelled, live]))).toEqual({ - code: "ERR_SQLITE_QUERY_CANCELLED", - message: "Query cancelled", - }); - expect(await live).toEqual([{ x: 2 }]); - }); - - test("cancel() before execute() rejects instead of running", async () => { - await using sql = new SQL("sqlite://:memory:"); - await sql`CREATE TABLE cancel_before_execute (id INTEGER)`; - const query = sql`INSERT INTO cancel_before_execute VALUES (1)`; - query.cancel(); - query.execute(); - - expect(await settle(query)).toEqual({ code: "ERR_SQLITE_QUERY_CANCELLED", message: "Query cancelled" }); - expect(await sql`SELECT count(*) AS n FROM cancel_before_execute`).toEqual([{ n: 0 }]); - }); -}); - -// A query that never runs opens no connection, so the server does not need to exist. -test.each([ - ["postgres://u:p@127.0.0.1:9/db", "ERR_POSTGRES_QUERY_CANCELLED"], - ["mysql://u:p@127.0.0.1:9/db", "ERR_MYSQL_QUERY_CANCELLED"], -])("cancel() before the query runs rejects for %s", async (url, code) => { - await using remote = new SQL(url); - const query = remote`SELECT 1 AS x`; - query.cancel(); - - expect(await settle(query)).toEqual({ code, message: "Query cancelled" }); -}); From e72981dd4d4116d40a6b1e9369c8326c12cc48ee Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 24 Sep 2026 14:27:44 +0000 Subject: [PATCH 13/34] sql: shorten the discard_response doc comment --- src/sql_jsc/postgres/PostgresSQLQuery.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/sql_jsc/postgres/PostgresSQLQuery.rs b/src/sql_jsc/postgres/PostgresSQLQuery.rs index 75c690f97d8a..955ecf6c4437 100644 --- a/src/sql_jsc/postgres/PostgresSQLQuery.rs +++ b/src/sql_jsc/postgres/PostgresSQLQuery.rs @@ -77,8 +77,7 @@ pub struct Flags { pub(crate) binary: bool, pub(crate) bigint: bool, pub(crate) simple: bool, - /// Rejected while in flight (an undecodable row, a cancel behind the FIFO head): its - /// response is skipped until `ReadyForQuery`. + /// Rejected while in flight: its response is skipped until `ReadyForQuery`. pub(crate) discard_response: bool, /// Which connection counter this request's dispatch incremented; reset to /// `None` when `finish_request` consumes that contribution, so the From ae6e96af1b4d7658405c3e5b4b0e0adbf4a7da6b Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 24 Sep 2026 15:10:50 +0000 Subject: [PATCH 14/34] sql: say in the error when a cancelled query still runs on the server A query that is written behind another one cannot be stopped on the server. It rejected with the same error as a query that was never sent, so a caller could not tell that a write still takes effect. It now carries a hint, the way an undecodable row does. The docs and the cancel() JSDoc described the cancel of a running query as a guarantee. It is a request: the query resolves if it finishes first. --- docs/runtime/sql.mdx | 11 +++++----- packages/bun-types/sql.d.ts | 15 ++++++++----- src/sql_jsc/postgres/PostgresSQLQuery.rs | 26 ++++++++++++++--------- test/js/sql/postgres-query-cancel.test.ts | 9 ++++++-- 4 files changed, 39 insertions(+), 22 deletions(-) diff --git a/docs/runtime/sql.mdx b/docs/runtime/sql.mdx index d57ce124f795..763e28259ec4 100644 --- a/docs/runtime/sql.mdx +++ b/docs/runtime/sql.mdx @@ -469,8 +469,7 @@ const result = await sql.unsafe("SELECT * FROM users WHERE id = :id", { id: 1 }) ### Execute and Cancelling Queries Queries are lazy: they only start executing when awaited or run with `.execute()`. -To cancel a running query, call `cancel()` on the query object. A cancelled query -rejects instead of resolving. +To cancel a query, call `cancel()` on the query object. ```ts const query = sql`SELECT pg_sleep(30)`.execute(); @@ -480,9 +479,11 @@ setTimeout(() => query.cancel(), 100); await query; ``` -PostgreSQL can only stop a running query from a separate connection, so `cancel()` -opens one and sends a `CancelRequest` on it. A query that has not reached the -server yet never runs at all, and rejects with `ERR_POSTGRES_QUERY_CANCELLED`. +On PostgreSQL, what `cancel()` does depends on how far the query got: + +- A query that Bun has not sent yet never runs. It rejects with `ERR_POSTGRES_QUERY_CANCELLED`. +- A query that the server is running can only be stopped from a separate connection, so Bun opens one and sends a `CancelRequest` on it. This is a request. If the server stops the query, the query rejects with SQLSTATE `57014`. If the query finishes first, it resolves as usual. +- A query that Bun already sent behind another query on the same connection also rejects with `ERR_POSTGRES_QUERY_CANCELLED`, but the server still runs it. The `hint` of the error says so. An `INSERT` or `UPDATE` in such a query still takes effect, so do not retry it blindly. --- diff --git a/packages/bun-types/sql.d.ts b/packages/bun-types/sql.d.ts index 3956a75bc3b1..37d0d6142e94 100644 --- a/packages/bun-types/sql.d.ts +++ b/packages/bun-types/sql.d.ts @@ -464,12 +464,17 @@ declare module "bun" { cancelled: boolean; /** - * Cancels the query and rejects its promise with the adapter's - * query-cancelled error (for example `ERR_POSTGRES_QUERY_CANCELLED`). + * Requests cancellation of the query. * - * For PostgreSQL, a query the backend has already started is stopped with a - * `CancelRequest` sent on a second connection, and rejects with whatever the - * server reports instead (SQLSTATE 57014). + * A query that has not been sent to the database never runs. It rejects + * with the adapter's query-cancelled error (for example + * `ERR_POSTGRES_QUERY_CANCELLED`). + * + * For PostgreSQL, a query the server is running is cancelled with a + * `CancelRequest` on a second connection. If the server stops the query, it + * rejects with SQLSTATE 57014. If the query finishes first, it resolves as + * usual. A query that was already sent behind another query rejects with + * `ERR_POSTGRES_QUERY_CANCELLED` and a `hint`, but the server still runs it. */ cancel(): Query; diff --git a/src/sql_jsc/postgres/PostgresSQLQuery.rs b/src/sql_jsc/postgres/PostgresSQLQuery.rs index 955ecf6c4437..bde090e84556 100644 --- a/src/sql_jsc/postgres/PostgresSQLQuery.rs +++ b/src/sql_jsc/postgres/PostgresSQLQuery.rs @@ -14,7 +14,7 @@ use super::PostgresSQLConnection; use super::PostgresSQLStatement; use super::Signature; use super::command_tag_jsc::CommandTagJsc; -use super::error_jsc::postgres_error_to_js; +use super::error_jsc::{postgres_error_to_js, postgres_error_to_js_with_hint}; use super::postgres_request as PostgresRequest; use super::postgres_sql_connection; use super::postgres_sql_statement::Status as StatementStatus; @@ -868,20 +868,26 @@ impl PostgresSQLQuery { // A CancelRequest names the backend process, not a statement, so it only // ever stops the FIFO head. Anything else is settled locally. - if status == Status::Pending || !connection.is_current_request(this) { + if status == Status::Pending { + // Nothing on the wire yet: a Fail entry is discarded, never written. let err = postgres_error_to_js( global_object, Some(b"Query cancelled"), AnyPostgresError::QueryCancelled, ); - if status == Status::Pending { - // Nothing on the wire yet: a Fail entry is discarded, never written. - connection.finish_request(this); - this.on_js_error(err, global_object); - } else { - // Already on the wire: the backend will answer it regardless. - this.reject_in_flight(err, global_object); - } + connection.finish_request(this); + this.on_js_error(err, global_object); + return Ok(JSValue::UNDEFINED); + } + if !connection.is_current_request(this) { + // Already on the wire: the backend runs it regardless, so the error says so. + let err = postgres_error_to_js_with_hint( + global_object, + Some(b"Query cancelled"), + Some(b"The server already received this query and still runs it. Bun discards the result."), + AnyPostgresError::QueryCancelled, + ); + this.reject_in_flight(err, global_object); return Ok(JSValue::UNDEFINED); } diff --git a/test/js/sql/postgres-query-cancel.test.ts b/test/js/sql/postgres-query-cancel.test.ts index faec79f9d5ae..246b7f7ea10e 100644 --- a/test/js/sql/postgres-query-cancel.test.ts +++ b/test/js/sql/postgres-query-cancel.test.ts @@ -233,11 +233,13 @@ test("cancel() on a queued query does not cancel the one the backend is running" ); queued.cancel(); + // No hint: this query never reaches the server. const err = await queuedSettled; - expect({ name: err.name, code: err.code, message: err.message }).toEqual({ + expect({ name: err.name, code: err.code, message: err.message, hint: err.hint }).toEqual({ name: "PostgresError", code: "ERR_POSTGRES_QUERY_CANCELLED", message: "Query cancelled", + hint: undefined, }); server.reply( @@ -342,11 +344,14 @@ test("cancel() on a pipelined query does not cancel the one the backend is runni pipelined.cancel(); + // The hint tells this case apart from a query that was never sent: the backend + // still runs this one, so a retry of a write would apply it twice. const err = await pipelinedSettled; - expect({ name: err.name, code: err.code, message: err.message }).toEqual({ + expect({ name: err.name, code: err.code, message: err.message, hint: err.hint }).toEqual({ name: "PostgresError", code: "ERR_POSTGRES_QUERY_CANCELLED", message: "Query cancelled", + hint: "The server already received this query and still runs it. Bun discards the result.", }); // No CancelRequest went out, so the running query was left alone. expect(server.connections).toBe(1); From 74fb430281f462f97d0f795c1261ed79d5f6ebe8 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 24 Sep 2026 20:01:24 +0000 Subject: [PATCH 15/34] sql: pass the port of the cancel connection as a number connectionInfo.port is typed string | number, and net.connect takes a number. The typecheck of the built-in modules rejected the call. --- src/js/internal/sql/postgres.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/js/internal/sql/postgres.ts b/src/js/internal/sql/postgres.ts index 79191ac31f1e..5c1e191f40c2 100644 --- a/src/js/internal/sql/postgres.ts +++ b/src/js/internal/sql/postgres.ts @@ -432,7 +432,7 @@ class PostgresAdapter const net = require("node:net"); // net.connect returns before the handshake, so the timeout covers it too. - const socket = net.connect(path ? { path } : { host: hostname, port }); + const socket = net.connect(path ? { path } : { host: hostname, port: Number(port) }); socket.setTimeout(CANCEL_REQUEST_TIMEOUT_MS); socket.on("timeout", () => socket.destroy()); // Best effort: a cancel that never arrives leaves the query running. From f3d7df85bc6a76a7c156f3302c315246bfe112da Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 25 Sep 2026 01:38:09 +0000 Subject: [PATCH 16/34] sql(postgres): move the allocate-and-dial block of createConnection into PostgresSQLConnection::open createConnection parsed its JavaScript arguments and then allocated the connection, dialed it and wrapped it for JS, all in one function. The second half now lives in PostgresSQLConnection::open, which takes a ConnectParams and the socket group, so that native code can open a connection without a call frame. createConnection fills ConnectParams from its arguments and calls it. No statement changes. --- src/sql_jsc/postgres/PostgresSQLConnection.rs | 293 +++++++++++------- 1 file changed, 180 insertions(+), 113 deletions(-) diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index edc8c4b66725..f197ee9100b9 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -1174,129 +1174,196 @@ pub(crate) fn call(global_object: &JSGlobalObject, callframe: &CallFrame) -> JsR } } - let on_connect = arguments[9]; - let on_close = arguments[10]; - let idle_timeout = arguments[11].to_int32(); - let connection_timeout = arguments[12].to_int32(); - let max_lifetime = arguments[13].to_int32(); - let use_unnamed_prepared_statements = arguments[14].as_boolean(); - - let ptr: *mut PostgresSQLConnection = - bun_core::heap::into_raw(Box::new(PostgresSQLConnection { - socket: JsCell::new(Socket::SocketTcp(uws::SocketTCP { - socket: uws::InternalSocket::Detached, - })), - status: Cell::new(Status::Connecting), - ref_count: Cell::new(1), - write_buffer: JsCell::new(OffsetByteList::default()), - write_epoch: Cell::new(0), - read_buffer: JsCell::new(OffsetByteList::default()), - last_message_start: Cell::new(0), - requests: JsCell::new(PostgresRequest::Queue::new()), - pipelined_requests: Cell::new(0), - nonpipelinable_requests: Cell::new(0), - pending_requests: Cell::new(0), - poll_ref: JsCell::new(KeepAlive::default()), - global_object: BackRef::new(global_object), - vm: BackRef::from( - core::ptr::NonNull::new(VirtualMachine::get_mut_ptr()).expect("vm singleton"), - ), - statements: JsCell::new(PreparedStatementsMap::default()), - prepared_statement_id: Cell::new(0), - pending_activity_count: AtomicU32::new(0), - js_value: JsCell::new(crate::jsc::JsRef::empty()), - backend_parameters: JsCell::new(StringMap::init(true)), - database, + let hostname = args.hostname_str.to_utf8(); + PostgresSQLConnection::open( + global_object, + vm.postgres_socket_group::(context), + ConnectParams { + hostname: hostname.slice(), + port: args.port, + options_buf, user: username, password, - path, + database, options, - options_buf, - authentication_state: JsCell::new(AuthenticationState::Pending), + path, secure, tls_config, - tls_status: Cell::new(if args.ssl_mode != SSLMode::Disable { - TLSStatus::Pending - } else { - TLSStatus::None - }), ssl_mode: args.ssl_mode, - idle_timeout_interval_ms: u32::try_from(idle_timeout).expect("int cast"), - connection_timeout_ms: u32::try_from(connection_timeout).expect("int cast"), - flags: Cell::new(if use_unnamed_prepared_statements { - ConnectionFlags::USE_UNNAMED_PREPARED_STATEMENTS + idle_timeout: arguments[11].to_int32(), + connection_timeout: arguments[12].to_int32(), + max_lifetime: arguments[13].to_int32(), + use_unnamed_prepared_statements: arguments[14].as_boolean(), + on_connect: arguments[9], + on_close: arguments[10], + }, + ) +} + +/// What `PostgresSQLConnection::open` builds a connection from. +pub(crate) struct ConnectParams<'a> { + /// Dialed when `path` is empty. + pub hostname: &'a [u8], + pub port: i32, + /// The five slices below point into it. + pub options_buf: Box<[u8]>, + pub user: bun_ptr::RawSlice, + pub password: bun_ptr::RawSlice, + pub database: bun_ptr::RawSlice, + pub options: bun_ptr::RawSlice, + pub path: bun_ptr::RawSlice, + pub secure: Option, + pub tls_config: jsc::api::ServerConfig::SSLConfig, + pub ssl_mode: SSLMode, + pub idle_timeout: i32, + pub connection_timeout: i32, + pub max_lifetime: i32, + pub use_unnamed_prepared_statements: bool, + pub on_connect: JSValue, + pub on_close: JSValue, +} + +impl PostgresSQLConnection { + /// Allocates the connection, dials it in `group` and wraps it for JS. + pub(crate) fn open( + global_object: &JSGlobalObject, + group: &mut bun_uws::SocketGroup, + params: ConnectParams<'_>, + ) -> JsResult { + let ConnectParams { + hostname, + port, + options_buf, + user: username, + password, + database, + options, + path, + secure, + tls_config, + ssl_mode, + idle_timeout, + connection_timeout, + max_lifetime, + use_unnamed_prepared_statements, + on_connect, + on_close, + } = params; + + let ptr: *mut PostgresSQLConnection = + bun_core::heap::into_raw(Box::new(PostgresSQLConnection { + socket: JsCell::new(Socket::SocketTcp(uws::SocketTCP { + socket: uws::InternalSocket::Detached, + })), + status: Cell::new(Status::Connecting), + ref_count: Cell::new(1), + write_buffer: JsCell::new(OffsetByteList::default()), + write_epoch: Cell::new(0), + read_buffer: JsCell::new(OffsetByteList::default()), + last_message_start: Cell::new(0), + requests: JsCell::new(PostgresRequest::Queue::new()), + pipelined_requests: Cell::new(0), + nonpipelinable_requests: Cell::new(0), + pending_requests: Cell::new(0), + poll_ref: JsCell::new(KeepAlive::default()), + global_object: BackRef::new(global_object), + vm: BackRef::from( + core::ptr::NonNull::new(VirtualMachine::get_mut_ptr()).expect("vm singleton"), + ), + statements: JsCell::new(PreparedStatementsMap::default()), + prepared_statement_id: Cell::new(0), + pending_activity_count: AtomicU32::new(0), + js_value: JsCell::new(crate::jsc::JsRef::empty()), + backend_parameters: JsCell::new(StringMap::init(true)), + database, + user: username, + password, + path, + options, + options_buf, + authentication_state: JsCell::new(AuthenticationState::Pending), + secure, + tls_config, + tls_status: Cell::new(if ssl_mode != SSLMode::Disable { + TLSStatus::Pending + } else { + TLSStatus::None + }), + ssl_mode, + idle_timeout_interval_ms: u32::try_from(idle_timeout).expect("int cast"), + connection_timeout_ms: u32::try_from(connection_timeout).expect("int cast"), + flags: Cell::new(if use_unnamed_prepared_statements { + ConnectionFlags::USE_UNNAMED_PREPARED_STATEMENTS + } else { + ConnectionFlags::empty() + }), + timer: JsCell::new(EventLoopTimer::init_paused( + EventLoopTimerTag::PostgresSQLConnectionTimeout, + )), + max_lifetime_interval_ms: u32::try_from(max_lifetime).expect("int cast"), + max_lifetime_timer: JsCell::new(EventLoopTimer::init_paused( + EventLoopTimerTag::PostgresSQLConnectionMaxLifetime, + )), + auto_flusher: JsCell::new(AutoFlusher::default()), + channel_names: JsCell::new(Vec::new()), + })); + + // `heap::into_raw` is `Box::into_raw` — never null. Sole owner until + // `to_js` below. R-2: every field is interior-mutable, so a shared + // `ParentRef` deref is sufficient for the writes below. + let this = ParentRef::from(core::ptr::NonNull::new(ptr).expect("heap::into_raw non-null")); + + { + // Postgres always opens plain TCP first (SSLRequest happens in-band), + // so even `ssl_mode != .disable` lands in the TCP group; `setupTLS()` + // adopts into `postgres_tls_group` after the server's `S`. + let path_slice = this.path.slice(); + let result = if !path_slice.is_empty() { + uws::SocketTCP::connect_unix_group( + group, + uws::SocketKind::Postgres, + None, + path_slice, + ptr, + false, + ) } else { - ConnectionFlags::empty() - }), - timer: JsCell::new(EventLoopTimer::init_paused( - EventLoopTimerTag::PostgresSQLConnectionTimeout, - )), - max_lifetime_interval_ms: u32::try_from(max_lifetime).expect("int cast"), - max_lifetime_timer: JsCell::new(EventLoopTimer::init_paused( - EventLoopTimerTag::PostgresSQLConnectionMaxLifetime, - )), - auto_flusher: JsCell::new(AutoFlusher::default()), - channel_names: JsCell::new(Vec::new()), - })); + uws::SocketTCP::connect_group( + group, + uws::SocketKind::Postgres, + None, + hostname, + port, + ptr, + false, + ) + }; - // `heap::into_raw` is `Box::into_raw` — never null. Sole owner until - // `to_js` below. R-2: every field is interior-mutable, so a shared - // `ParentRef` deref is sufficient for the writes below. - let this = ParentRef::from(core::ptr::NonNull::new(ptr).expect("heap::into_raw non-null")); - - { - let hostname = args.hostname_str.to_utf8(); - - // Postgres always opens plain TCP first (SSLRequest happens in-band), - // so even `ssl_mode != .disable` lands in the TCP group; `setupTLS()` - // adopts into `postgres_tls_group` after the server's `S`. - let group = vm.postgres_socket_group::(context); - let path_slice = this.path.slice(); - let result = if !path_slice.is_empty() { - uws::SocketTCP::connect_unix_group( - group, - uws::SocketKind::Postgres, - None, - path_slice, - ptr, - false, - ) - } else { - uws::SocketTCP::connect_group( - group, - uws::SocketKind::Postgres, - None, - hostname.slice(), - args.port, - ptr, - false, - ) - }; + this.socket.set(Socket::SocketTcp(match result { + Ok(s) => s, + Err(err) => { + // SAFETY: fresh allocation, sole ref. + drop(unsafe { bun_core::heap::take(ptr) }); + return Err(global_object.throw_error( + bun_jsc::CrateError::from(err), + "failed to connect to postgresql", + )); + } + })); + } - this.socket.set(Socket::SocketTcp(match result { - Ok(s) => s, - Err(err) => { - // SAFETY: fresh allocation, sole ref. - drop(unsafe { bun_core::heap::take(ptr) }); - return Err(global_object.throw_error( - bun_jsc::CrateError::from(err), - "failed to connect to postgresql", - )); - } - })); + // only call toJS if connectUnixAnon does not fail immediately + this.update_has_pending_activity(); + this.reset_connection_timeout(); + this.poll_ref.with_mut(|r| r.ref_(this.vm_ctx())); + let js_value = js::to_js(ptr, global_object); + js_value.ensure_still_alive(); + this.js_value.set(crate::jsc::JsRef::init_weak(js_value)); + js::onconnect_set_cached(js_value, global_object, on_connect); + js::onclose_set_cached(js_value, global_object, on_close); + bun_analytics::features::postgres_connections.fetch_add(1, Ordering::Relaxed); + Ok(js_value) } - - // only call toJS if connectUnixAnon does not fail immediately - this.update_has_pending_activity(); - this.reset_connection_timeout(); - this.poll_ref.with_mut(|r| r.ref_(this.vm_ctx())); - let js_value = js::to_js(ptr, global_object); - js_value.ensure_still_alive(); - this.js_value.set(crate::jsc::JsRef::init_weak(js_value)); - js::onconnect_set_cached(js_value, global_object, on_connect); - js::onclose_set_cached(js_value, global_object, on_close); - bun_analytics::features::postgres_connections.fetch_add(1, Ordering::Relaxed); - Ok(js_value) } pub struct SocketHandler; From 78dcace13b42d2352eb85a8c068cd5d284f367c0 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 25 Sep 2026 01:47:12 +0000 Subject: [PATCH 17/34] sql(postgres): open the cancel connection from the session, in native code The cancel connection was a node:net socket that the adapter opened with the host and port of the options. It did not follow the rules of the session's connection: it was plaintext on a TLS session, it could not dial a bracketed IPv6 host, and it resolved the host name again. The session now opens it itself. PostgresSQLConnection::send_cancel_request dials the peer address or unix socket of the session through PostgresSQLConnection::open, with the TLS state of the session, and the new connection writes the CancelRequest where a session writes its StartupMessage. It has one time budget from dial to hang-up, ends on the first thing the server does, and closes without waiting for the peer. The cancel key does not enter JavaScript. --- docs/runtime/sql.mdx | 2 +- src/js/internal/sql/postgres.ts | 21 -- src/js/internal/sql/query.ts | 8 +- src/js/internal/sql/shared.ts | 3 - src/runtime/hw_exports.rs | 6 + src/sql/shared/ConnectionFlags.rs | 2 + src/sql_jsc/jsc.rs | 13 +- src/sql_jsc/postgres/PostgresSQLConnection.rs | 147 +++++++++++++- src/sql_jsc/postgres/PostgresSQLQuery.rs | 16 +- test/js/sql/postgres-query-cancel.test.ts | 186 ++++++++++++++++-- 10 files changed, 333 insertions(+), 71 deletions(-) diff --git a/docs/runtime/sql.mdx b/docs/runtime/sql.mdx index 763e28259ec4..0d0044291750 100644 --- a/docs/runtime/sql.mdx +++ b/docs/runtime/sql.mdx @@ -482,7 +482,7 @@ await query; On PostgreSQL, what `cancel()` does depends on how far the query got: - A query that Bun has not sent yet never runs. It rejects with `ERR_POSTGRES_QUERY_CANCELLED`. -- A query that the server is running can only be stopped from a separate connection, so Bun opens one and sends a `CancelRequest` on it. This is a request. If the server stops the query, the query rejects with SQLSTATE `57014`. If the query finishes first, it resolves as usual. +- A query that the server is running can only be stopped from a separate connection. Bun opens one to the same server, encrypted when the session is, and sends a `CancelRequest` on it. This is a request. If the server stops the query, the query rejects with SQLSTATE `57014`. If the query finishes first, it resolves as usual. - A query that Bun already sent behind another query on the same connection also rejects with `ERR_POSTGRES_QUERY_CANCELLED`, but the server still runs it. The `hint` of the error says so. An `INSERT` or `UPDATE` in such a query still takes effect, so do not retry it blindly. --- diff --git a/src/js/internal/sql/postgres.ts b/src/js/internal/sql/postgres.ts index 5c1e191f40c2..c2240b8353cf 100644 --- a/src/js/internal/sql/postgres.ts +++ b/src/js/internal/sql/postgres.ts @@ -34,8 +34,6 @@ const { const cmds = ["", "INSERT", "DELETE", "UPDATE", "MERGE", "SELECT", "MOVE", "FETCH", "COPY"]; -const CANCEL_REQUEST_TIMEOUT_MS = 5_000; - const escapeBackslash = /\\/g; const escapeQuote = /"/g; @@ -422,25 +420,6 @@ class PostgresAdapter return '"' + str.replaceAll('"', '""').replaceAll(".", '"."') + '"'; } - /** - * Plaintext on purpose: the backend handles CancelRequest before SSL - * negotiation, and the packet carries only the pid/secret the server itself - * issued. This matches libpq's PQcancel(). - */ - sendCancelRequest(request: Uint8Array): void { - const { path, hostname, port } = this.connectionInfo; - const net = require("node:net"); - - // net.connect returns before the handshake, so the timeout covers it too. - const socket = net.connect(path ? { path } : { host: hostname, port: Number(port) }); - socket.setTimeout(CANCEL_REQUEST_TIMEOUT_MS); - socket.on("timeout", () => socket.destroy()); - // Best effort: a cancel that never arrives leaves the query running. - socket.on("error", () => {}); - // A write queued before connect suppresses net.Socket's timeout; write after. - socket.on("connect", () => socket.end(request)); - } - connectionClosedError() { return new PostgresError("Connection closed", { code: "ERR_POSTGRES_CONNECTION_CLOSED", diff --git a/src/js/internal/sql/query.ts b/src/js/internal/sql/query.ts index 6a522b4e4ce8..331432cd8ed2 100644 --- a/src/js/internal/sql/query.ts +++ b/src/js/internal/sql/query.ts @@ -15,8 +15,7 @@ const PublicPromise = Promise; export interface BaseQueryHandle { done?(): void; - /** Returns bytes the adapter must deliver out-of-band, or undefined. */ - cancel?(): Uint8Array | undefined; + cancel?(): void; setMode(mode: SQLQueryResultMode): void; run(connection: Connection, query: Query): void | Promise; } @@ -218,10 +217,7 @@ class Query> extends PublicPromise { const handle = this.#getQueryHandle(); if (handle) { - const cancelRequest = handle.cancel?.(); - if (cancelRequest) { - this[_adapter].sendCancelRequest?.(cancelRequest); - } + handle.cancel?.(); } } diff --git a/src/js/internal/sql/shared.ts b/src/js/internal/sql/shared.ts index 71a4364aff10..8f9cd3d94274 100644 --- a/src/js/internal/sql/shared.ts +++ b/src/js/internal/sql/shared.ts @@ -2266,9 +2266,6 @@ export interface DatabaseAdapter { connectionClosedError(): Error; queryCancelledError(): Error; invalidTransactionStateError(message: string): Error; - - /** Deliver the bytes `QueryHandle.cancel()` returned on a separate connection. */ - sendCancelRequest?(request: Uint8Array): void; } export default { diff --git a/src/runtime/hw_exports.rs b/src/runtime/hw_exports.rs index db72f894766e..1f0d265f46c7 100644 --- a/src/runtime/hw_exports.rs +++ b/src/runtime/hw_exports.rs @@ -257,6 +257,11 @@ mod sql_hooks { // `ssl_config_from_js`; sql_jsc's `SSLConfig::drop` guards null/double. drop(unsafe { bun_core::heap::take(this.cast::()) }); } + unsafe fn ssl_config_clone(this: *const c_void) -> *mut c_void { + // SAFETY: `this` is a live boxed `SSLConfig` from `ssl_config_from_js`. + let config = unsafe { &*this.cast::() }.clone(); + bun_core::heap::into_raw(Box::new(config)).cast::() + } unsafe fn ssl_config_as_usockets_client( this: *const c_void, ) -> bun_uws::us_bun_socket_context_options_t { @@ -298,6 +303,7 @@ mod sql_hooks { ssl_ctx_get_or_create, ssl_config_from_js, ssl_config_free, + ssl_config_clone, ssl_config_as_usockets_client, ssl_config_server_name, ssl_config_reject_unauthorized, diff --git a/src/sql/shared/ConnectionFlags.rs b/src/sql/shared/ConnectionFlags.rs index ec85975fffe3..1c7ce9e58119 100644 --- a/src/sql/shared/ConnectionFlags.rs +++ b/src/sql/shared/ConnectionFlags.rs @@ -10,6 +10,8 @@ bitflags! { const HAS_BACKPRESSURE = 1 << 4; /// `ref()` was called; `on_data` must not unref the idle connection. const KEEP_ALIVE_REQUESTED = 1 << 5; + /// Postgres: exists only to deliver a CancelRequest in place of the StartupMessage. + const IS_CANCEL_REQUEST = 1 << 6; } } diff --git a/src/sql_jsc/jsc.rs b/src/sql_jsc/jsc.rs index dde23054c2cc..68b501ca1c02 100644 --- a/src/sql_jsc/jsc.rs +++ b/src/sql_jsc/jsc.rs @@ -28,7 +28,7 @@ use core::ptr::NonNull; pub use bun_jsc::{ CallFrame, ErrorBuilder, ErrorCode, ExternColumnIdentifier, GlobalRef, JSArrayIterator, - JSGlobalObject, JSObject, JSType, JSUint8Array, JSValue, JsCell, JsError, JsRef, JsResult, + JSGlobalObject, JSObject, JSType, JSValue, JsCell, JsError, JsRef, JsResult, MarkedArgumentBuffer, StringJsc, Strong, StrongOptional, bun_string_jsc, }; @@ -238,6 +238,8 @@ pub struct SqlRuntimeHooks { pub ssl_config_from_js: unsafe fn(&JSGlobalObject, JSValue) -> *mut c_void, /// Drop a boxed `SSLConfig` returned by `ssl_config_from_js`. pub ssl_config_free: unsafe fn(*mut c_void), + /// Copy a boxed `SSLConfig` (caller frees via `ssl_config_free`). + pub ssl_config_clone: unsafe fn(*const c_void) -> *mut c_void, /// `SSLConfig::asUSocketsForClientVerification`. pub ssl_config_as_usockets_client: unsafe fn(*const c_void) -> bun_uws::us_bun_socket_context_options_t, @@ -477,6 +479,15 @@ pub mod api { } } + impl Clone for SSLConfig { + fn clone(&self) -> Self { + Self(self.0.and_then(|p| { + // SAFETY: `p` is a live boxed SSLConfig; the hook returns a fresh box. + NonNull::new(unsafe { (hooks().ssl_config_clone)(p.as_ptr()) }) + })) + } + } + impl SSLConfig { /// `SSLConfig.server_name` — the SNI hostname C string, or null /// when unset / default. diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index ea90c0c643f8..78e9ec8be3a6 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -52,6 +52,9 @@ pub use bun_sql::postgres::TLSStatus as TlsStatus; type Socket = uws::AnySocket; +/// From dial to hang-up, for the connection that delivers a CancelRequest. +const CANCEL_REQUEST_TIMEOUT_MS: i32 = 5_000; + bun_core::define_scoped_log!(debug, Postgres, visible); const MAX_PIPELINE_SIZE: usize = u16::MAX as usize; // about 64KB per connection @@ -606,9 +609,18 @@ impl PostgresSQLConnection { ); } + fn is_cancel_request(&self) -> bool { + self.flags + .get() + .contains(ConnectionFlags::IS_CANCEL_REQUEST) + } + fn start(&self) { self.setup_max_lifetime_timer_if_necessary(); - self.reset_connection_timeout(); + // A cancel connection has one time budget, from dial to hang-up. + if !self.is_cancel_request() { + self.reset_connection_timeout(); + } self.send_startup_message(); self.drain_internal(); @@ -841,6 +853,13 @@ impl PostgresSQLConnection { } debug!("sendStartupMessage"); self.status.set(Status::SentStartupMessage); + if self.is_cancel_request() { + let packet = self.backend_key_data.get().cancel_request(); + if let Err(err) = self.writer().write(&packet) { + self.fail(b"Failed to write cancel request", err); + } + return; + } let msg = protocol::StartupMessage { user: Data::Temporary(self.user), database: Data::Temporary(self.database), @@ -988,6 +1007,11 @@ impl PostgresSQLConnection { pub(crate) fn on_data(&self, data: &[u8]) { let _guard = self.ref_guard(); + if self.is_cancel_request() && self.status.get() == Status::SentStartupMessage { + // A server answers a CancelRequest by hanging up, so this is no server to talk to. + self.fail(b"Connection closed", AnyPostgresError::ConnectionClosed); + return; + } self.update_flags(|f| f.insert(ConnectionFlags::IS_PROCESSING_DATA)); if self.status.get() == Status::Connected { @@ -1197,6 +1221,7 @@ pub(crate) fn call(global_object: &JSGlobalObject, callframe: &CallFrame) -> JsR use_unnamed_prepared_statements: arguments[14].as_boolean(), on_connect: arguments[9], on_close: arguments[10], + cancel: None, }, ) } @@ -1222,6 +1247,8 @@ pub(crate) struct ConnectParams<'a> { pub use_unnamed_prepared_statements: bool, pub on_connect: JSValue, pub on_close: JSValue, + /// Set for a connection that only delivers a CancelRequest for this backend. + pub cancel: Option, } impl PostgresSQLConnection { @@ -1249,7 +1276,14 @@ impl PostgresSQLConnection { use_unnamed_prepared_statements, on_connect, on_close, + cancel, } = params; + let mut flags = ConnectionFlags::empty(); + flags.set( + ConnectionFlags::USE_UNNAMED_PREPARED_STATEMENTS, + use_unnamed_prepared_statements, + ); + flags.set(ConnectionFlags::IS_CANCEL_REQUEST, cancel.is_some()); let ptr: *mut PostgresSQLConnection = bun_core::heap::into_raw(Box::new(PostgresSQLConnection { @@ -1276,7 +1310,7 @@ impl PostgresSQLConnection { pending_activity_count: AtomicU32::new(0), js_value: JsCell::new(crate::jsc::JsRef::empty()), backend_parameters: JsCell::new(StringMap::init(true)), - backend_key_data: JsCell::new(protocol::BackendKeyData::default()), + backend_key_data: JsCell::new(cancel.unwrap_or_default()), database, user: username, password, @@ -1294,11 +1328,7 @@ impl PostgresSQLConnection { ssl_mode, idle_timeout_interval_ms: u32::try_from(idle_timeout).expect("int cast"), connection_timeout_ms: u32::try_from(connection_timeout).expect("int cast"), - flags: Cell::new(if use_unnamed_prepared_statements { - ConnectionFlags::USE_UNNAMED_PREPARED_STATEMENTS - } else { - ConnectionFlags::empty() - }), + flags: Cell::new(flags), timer: JsCell::new(EventLoopTimer::init_paused( EventLoopTimerTag::PostgresSQLConnectionTimeout, )), @@ -1363,7 +1393,9 @@ impl PostgresSQLConnection { this.js_value.set(crate::jsc::JsRef::init_weak(js_value)); js::onconnect_set_cached(js_value, global_object, on_connect); js::onclose_set_cached(js_value, global_object, on_close); - bun_analytics::features::postgres_connections.fetch_add(1, Ordering::Relaxed); + if !this.is_cancel_request() { + bun_analytics::features::postgres_connections.fetch_add(1, Ordering::Relaxed); + } Ok(js_value) } } @@ -1582,7 +1614,12 @@ impl PostgresSQLConnection { // event loop need to be alive to close the socket self.poll_ref.with_mut(|r| r.ref_(self.vm_ctx())); // will unref on socket close - self.socket.get().close(uws::CloseKind::Normal); + self.socket.get().close(if self.is_cancel_request() { + // Not `Normal`: on TLS that waits for the peer's close_notify. + uws::CloseKind::Failure + } else { + uws::CloseKind::Normal + }); } // cleanup requests @@ -1619,6 +1656,98 @@ impl PostgresSQLConnection { .is_some_and(|f| core::ptr::eq(f.as_ptr(), request)) } + /// Asks the server, from a second connection, to cancel what the backend of this + /// session runs. That connection goes where this one went, to the same peer address + /// or unix socket, and is encrypted when this one is. + pub(crate) fn send_cancel_request(&self) { + let key = self.backend_key_data.get(); + // No BackendKeyData was ever received, so the server cannot be asked. + if key.process_id == 0 { + return; + } + let socket = self.socket.get(); + let uws::InternalSocket::Connected(raw) = *socket.socket() else { + return; + }; + + let mut hostname = [0u8; 46]; + let mut hostname_len = 0; + let mut port = 0; + if self.path.slice().is_empty() { + let mut address = [0u8; 16]; + let (peer, peer_port) = match socket { + Socket::SocketTcp(tcp) => (tcp.remote_address(&mut address), tcp.remote_port()), + Socket::SocketTls(tls) => (tls.remote_address(&mut address), tls.remote_port()), + }; + let (Some(peer), Some(peer_port)) = (peer, peer_port) else { + return; + }; + let ip: std::net::IpAddr = match *peer { + [a, b, c, d] => std::net::Ipv4Addr::new(a, b, c, d).into(), + _ => match <[u8; 16]>::try_from(peer) { + Ok(v6) => std::net::Ipv6Addr::from(v6).into(), + Err(_) => return, + }, + }; + use std::io::Write as _; + let mut unwritten = &mut hostname[..]; + if write!(unwritten, "{ip}").is_err() { + return; + } + let unwritten = unwritten.len(); + hostname_len = hostname.len() - unwritten; + port = i32::from(peer_port); + } + + let mut builder = bun_core::StringBuilder::default(); + builder.cap += self.path.slice().len() + 1; + let _ = builder.allocate(); + let path = bun_ptr::RawSlice::new(builder.append(self.path.slice())); + let options_buf = builder.move_to_slice(); + + // SAFETY: `raw` is the live connected socket of this session, in a group of its context. + let group = unsafe { + bun_jsc::rare_data::SocketGroups::of((*raw).group()) + .postgres_group::(self.vm_mut().uws_loop()) + }; + let opened = Self::open( + self.global(), + group, + ConnectParams { + hostname: &hostname[..hostname_len], + port, + options_buf, + user: bun_ptr::RawSlice::EMPTY, + password: bun_ptr::RawSlice::EMPTY, + database: bun_ptr::RawSlice::EMPTY, + options: bun_ptr::RawSlice::EMPTY, + path, + secure: self.secure.clone(), + tls_config: self.tls_config.clone(), + // Encrypted exactly when this session is, whatever `prefer` would allow. + ssl_mode: match (self.tls_status.get(), self.ssl_mode) { + (TLSStatus::SslOk, SSLMode::Prefer) => SSLMode::Require, + (TLSStatus::SslOk, mode) => mode, + _ => SSLMode::Disable, + }, + idle_timeout: 0, + connection_timeout: CANCEL_REQUEST_TIMEOUT_MS, + max_lifetime: 0, + use_unnamed_prepared_statements: false, + on_connect: JSValue::ZERO, + on_close: JSValue::ZERO, + cancel: Some(protocol::BackendKeyData { + process_id: key.process_id, + secret_key: key.secret_key, + }), + }, + ); + // Best effort: a cancel that cannot be dialed leaves the query running. + if opened.is_err() { + let _ = self.global().try_take_exception(); + } + } + /// Pop the FIFO head if it is still `request` (re-entrant JS may already /// have removed it), dropping the queue's ref. #[inline] diff --git a/src/sql_jsc/postgres/PostgresSQLQuery.rs b/src/sql_jsc/postgres/PostgresSQLQuery.rs index ad6c962c4dbe..5b8ebd57bc17 100644 --- a/src/sql_jsc/postgres/PostgresSQLQuery.rs +++ b/src/sql_jsc/postgres/PostgresSQLQuery.rs @@ -848,8 +848,6 @@ impl PostgresSQLQuery { Ok(JSValue::UNDEFINED) } - /// Returns the CancelRequest packet to deliver on a second connection, or - /// `undefined` when there is nothing for the server to stop. pub fn do_cancel( this: &Self, global_object: &JSGlobalObject, @@ -871,7 +869,7 @@ impl PostgresSQLQuery { // A CancelRequest names the backend process, not a statement, so it only // ever stops the FIFO head. Anything else is settled locally. if status == Status::Pending { - // Nothing on the wire yet: a Fail entry is discarded, never written. + // No Bind, Execute or Query of it is written, and a Fail entry never writes one. let err = postgres_error_to_js( global_object, Some(b"Query cancelled"), @@ -893,15 +891,7 @@ impl PostgresSQLQuery { return Ok(JSValue::UNDEFINED); } - // Copy out before the JS-heap allocation below can re-enter. - let (process_id, packet) = { - let key = connection.backend_key_data.get(); - (key.process_id, key.cancel_request()) - }; - // No BackendKeyData was ever received, so the server cannot be asked. - if process_id == 0 { - return Ok(JSValue::UNDEFINED); - } - crate::jsc::JSUint8Array::from_bytes_copy(global_object, &packet) + connection.send_cancel_request(); + Ok(JSValue::UNDEFINED) } } diff --git a/test/js/sql/postgres-query-cancel.test.ts b/test/js/sql/postgres-query-cancel.test.ts index 246b7f7ea10e..ada6d5b46947 100644 --- a/test/js/sql/postgres-query-cancel.test.ts +++ b/test/js/sql/postgres-query-cancel.test.ts @@ -10,7 +10,10 @@ // cancelled before it was dispatched never settled at all. import { SQL } from "bun"; import { expect, test } from "bun:test"; +import { isIPv6, isWindows, tempDir, tls as tlsCert } from "harness"; import net from "node:net"; +import { join } from "node:path"; +import tls from "node:tls"; import { pgAuthenticationOk, pgBackendKeyData, @@ -33,6 +36,9 @@ const SECRET_KEY = 13371337; // has already prepared). const TEXT_OID = 25; +// Int32(8) Int32(80877103): the one message a client sends in plaintext before TLS. +const SSL_REQUEST = Buffer.from([0, 0, 0, 8, 0x04, 0xd2, 0x16, 0x2f]); + /** * Scripted Postgres backend. * @@ -41,9 +47,17 @@ const TEXT_OID = 25; * unanswered the way a backend stuck inside pg_sleep() would leave them, and the * test writes every reply itself. A CancelRequest always arrives on the second * connection, because the first one is busy running the query. + * + * With `tls` every connection has to start with an SSLRequest. The backend answers + * `S` and reads everything else through TLS, and `plaintext` keeps what each + * connection sent in the clear. With `answersCancel` it answers a CancelRequest + * like the start of a session and does not hang up, which no real backend does. */ -async function backend() { +async function backend(options: { tls?: boolean; host?: string; socketPath?: string; answersCancel?: boolean } = {}) { + const host = options.host ?? "127.0.0.1"; + const plaintext: Buffer[] = []; const cancelPacket = Promise.withResolvers(); + const cancelConnectionClosed = Promise.withResolvers(); const queryConnectionClosed = Promise.withResolvers(); const sockets = new Set(); const waiters = new Map void>(); @@ -71,19 +85,42 @@ async function backend() { if (autoReply) queryConnection!.write(preparedReply()); } - const server = net.createServer(socket => { - sockets.add(socket); - socket.on("close", () => sockets.delete(socket)); - socket.on("error", () => {}); + const server = net.createServer(rawSocket => { + sockets.add(rawSocket); + rawSocket.on("close", () => sockets.delete(rawSocket)); + rawSocket.on("error", () => {}); + const connection = ++connections; + if (!options.tls) return serve(connection, rawSocket); + + let buffered = Buffer.alloc(0); + const onPlaintext = (data: Buffer) => { + buffered = Buffer.concat([buffered, data]); + if (buffered.length < SSL_REQUEST.length) return; + plaintext[connection - 1] = buffered.subarray(0, SSL_REQUEST.length); + // What follows the SSLRequest is the ClientHello: hand it to the TLS engine. + rawSocket.removeListener("data", onPlaintext); + rawSocket.pause(); + const leftover = buffered.subarray(SSL_REQUEST.length); + if (leftover.length) rawSocket.unshift(leftover); + rawSocket.write("S"); + const secure = new tls.TLSSocket(rawSocket, { isServer: true, ...tlsCert }); + secure.on("error", () => {}); + serve(connection, secure); + }; + rawSocket.on("data", onPlaintext); + }); - if (++connections > 1) { + function serve(connection: number, socket: net.Socket) { + if (connection > 1) { let buffered = Buffer.alloc(0); + socket.on("close", () => cancelConnectionClosed.resolve()); socket.on("data", data => { buffered = Buffer.concat([buffered, data]); if (buffered.length < 16) return; cancelPacket.resolve(buffered); // A real backend acts on the CancelRequest and hangs up. - socket.end(); + if (!options.answersCancel) return void socket.end(); + socket.write(Buffer.concat([pgAuthenticationOk(), pgReadyForQuery()])); }); return; } @@ -107,18 +144,28 @@ async function backend() { if (message === "S" || message === "Q") onQueryUnit(); }); }); - }); - await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); - const { port } = server.address() as net.AddressInfo; + } + await new Promise(resolve => + options.socketPath ? server.listen(options.socketPath, resolve) : server.listen(0, host, resolve), + ); + const port = options.socketPath ? 5432 : (server.address() as net.AddressInfo).port; return { - url: `postgres://postgres@127.0.0.1:${port}/postgres`, + url: `postgres://postgres@${net.isIPv6(host) ? `[${host}]` : host}:${port}/postgres`, + /** What each connection sent before TLS, by connection order. */ + plaintext, cancelPacket: cancelPacket.promise, + /** Resolves once the connection that carried the CancelRequest is closed. */ + cancelConnectionClosed: cancelConnectionClosed.promise, /** Resolves once the client has closed the connection its queries run on. */ queryConnectionClosed: queryConnectionClosed.promise, get connections() { return connections; }, + /** How many complete query units the client has sent. */ + get queryUnits() { + return queryUnits; + }, set autoReply(value: boolean) { autoReply = value; }, @@ -193,6 +240,108 @@ test.each(protocols)("cancel() on a running %s query sends a CancelRequest", asy }); }); +// The cancel connection has to reach the server the way the session does. A +// plaintext one leaks the cancel key of a TLS session, and a server that only +// accepts TLS never sees it. +test("cancel() on a TLS session sends the CancelRequest through TLS", async () => { + await using server = await backend({ tls: true }); + server.autoReply = false; + // `ca` makes the session verify-full, so the cancel connection only gets through + // the handshake if it uses the same TLS options. + await using sql = new SQL({ url: server.url, tls: { ca: tlsCert.cert }, max: 1, connectionTimeout: 5 }); + + const query = sql`select pg_sleep(10)`.execute(); + const settled = query.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + query.cancel(); + + expect(await server.cancelPacket).toEqual(pgCancelRequest(PROCESS_ID, SECRET_KEY)); + // Both connections sent an SSLRequest in the clear, and nothing else. + expect(server.plaintext).toEqual([SSL_REQUEST, SSL_REQUEST]); + + server.reply( + pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), + pgReadyForQuery(), + ); + expect((await settled).errno).toBe("57014"); +}); + +// URL parsing keeps the brackets of an IPv6 literal in the hostname. The session's +// connect strips them, so the cancel connection has to as well. +test.skipIf(!isIPv6())("cancel() reaches a server that is addressed by an IPv6 literal", async () => { + await using server = await backend({ host: "::1" }); + server.autoReply = false; + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + + const query = sql`select pg_sleep(10)`.execute(); + const settled = query.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + query.cancel(); + + expect(await server.cancelPacket).toEqual(pgCancelRequest(PROCESS_ID, SECRET_KEY)); + + server.reply( + pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), + pgReadyForQuery(), + ); + expect((await settled).errno).toBe("57014"); +}); + +test.skipIf(isWindows)("cancel() reaches a server on a unix socket", async () => { + using dir = tempDir("pg-cancel", {}); + const socketPath = join(String(dir), "pg.sock"); + await using server = await backend({ socketPath }); + server.autoReply = false; + await using sql = new SQL({ adapter: "postgres", path: socketPath, username: "postgres", max: 1 }); + + const query = sql`select pg_sleep(10)`.execute(); + const settled = query.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + query.cancel(); + + expect(await server.cancelPacket).toEqual(pgCancelRequest(PROCESS_ID, SECRET_KEY)); + + server.reply( + pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), + pgReadyForQuery(), + ); + expect((await settled).errno).toBe("57014"); +}); + +// The cancel connection carries one packet. It must not turn into a session, with +// no timeout and no owner, because a server answers it. +test("the cancel connection closes when the server answers it", async () => { + await using server = await backend({ answersCancel: true }); + server.autoReply = false; + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + + const query = sql`select pg_sleep(10)`.execute(); + const settled = query.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + query.cancel(); + + expect(await server.cancelPacket).toEqual(pgCancelRequest(PROCESS_ID, SECRET_KEY)); + await server.cancelConnectionClosed; + + server.reply( + pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), + pgReadyForQuery(), + ); + expect((await settled).errno).toBe("57014"); +}); + test("cancel() before the query is dispatched rejects it instead of hanging", async () => { await using server = await backend(); await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); @@ -208,8 +357,10 @@ test("cancel() before the query is dispatched rejects it instead of hanging", as code: "ERR_POSTGRES_QUERY_CANCELLED", message: "Query cancelled", }); - // Never even asked the pool for a connection. - expect(server.connections).toBe(0); + // The cancelled query never reaches the server: after a round trip for the next + // query, that query is the only one the server has seen. + expect(await sql`select 'next'`).toEqual([{ v: "ok" }]); + expect(server.queryUnits).toBe(1); }); test("cancel() on a queued query does not cancel the one the backend is running", async () => { @@ -250,7 +401,9 @@ test("cancel() on a queued query does not cancel the one the backend is running" ); expect(await runningSettled).toEqual([{ v: "kept" }]); - // No second connection was opened, so nothing was cancelled on the server. + // A cancel connection would have arrived by the end of one more round trip. + server.autoReply = true; + expect(await sql`select 'next'`).toEqual([{ v: "ok" }]); expect(server.connections).toBe(1); }); @@ -353,9 +506,6 @@ test("cancel() on a pipelined query does not cancel the one the backend is runni message: "Query cancelled", hint: "The server already received this query and still runs it. Bun discards the result.", }); - // No CancelRequest went out, so the running query was left alone. - expect(server.connections).toBe(1); - server.answerPrepared("kept"); expect(await runningSettled).toEqual([{ v: "kept" }]); @@ -365,4 +515,6 @@ test("cancel() on a pipelined query does not cancel the one the backend is runni server.answerPrepared("drained"); server.autoReply = true; expect(await sql`select 'c'`).toEqual([{ v: "ok" }]); + // Two round trips after the cancel, a cancel connection would have arrived. + expect(server.connections).toBe(1); }); From 81b63103bb07f7ca59d568705615cc4dc6105a9d Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 25 Sep 2026 02:28:11 +0000 Subject: [PATCH 18/34] sql: test that a cancel connection never goes out in the clear for a TLS session --- test/js/sql/postgres-query-cancel.test.ts | 94 +++++++++++++++++++++-- 1 file changed, 86 insertions(+), 8 deletions(-) diff --git a/test/js/sql/postgres-query-cancel.test.ts b/test/js/sql/postgres-query-cancel.test.ts index ada6d5b46947..d4c4f66563e0 100644 --- a/test/js/sql/postgres-query-cancel.test.ts +++ b/test/js/sql/postgres-query-cancel.test.ts @@ -10,7 +10,7 @@ // cancelled before it was dispatched never settled at all. import { SQL } from "bun"; import { expect, test } from "bun:test"; -import { isIPv6, isWindows, tempDir, tls as tlsCert } from "harness"; +import { expiredTls, isIPv6, isWindows, tempDir, tls as tlsCert } from "harness"; import net from "node:net"; import { join } from "node:path"; import tls from "node:tls"; @@ -50,10 +50,20 @@ const SSL_REQUEST = Buffer.from([0, 0, 0, 8, 0x04, 0xd2, 0x16, 0x2f]); * * With `tls` every connection has to start with an SSLRequest. The backend answers * `S` and reads everything else through TLS, and `plaintext` keeps what each - * connection sent in the clear. With `answersCancel` it answers a CancelRequest - * like the start of a session and does not hang up, which no real backend does. + * connection sent in the clear. + * + * `cancelConnection` makes the second connection meet a server no real backend is: + * one that answers a CancelRequest like the start of a session and does not hang + * up, one that declines TLS, or one whose certificate the session's CA did not sign. */ -async function backend(options: { tls?: boolean; host?: string; socketPath?: string; answersCancel?: boolean } = {}) { +async function backend( + options: { + tls?: boolean; + host?: string; + socketPath?: string; + cancelConnection?: "answers" | "declines-tls" | "other-certificate"; + } = {}, +) { const host = options.host ?? "127.0.0.1"; const plaintext: Buffer[] = []; const cancelPacket = Promise.withResolvers(); @@ -65,6 +75,7 @@ async function backend(options: { tls?: boolean; host?: string; socketPath?: str let connections = 0; let queryUnits = 0; let autoReply = true; + let cancelPacketSeen = false; // Answer a Parse+Describe+Bind+Execute with one text row: ParseComplete and // the two Describe replies, then the Execute replies. @@ -92,10 +103,19 @@ async function backend(options: { tls?: boolean; host?: string; socketPath?: str const connection = ++connections; if (!options.tls) return serve(connection, rawSocket); + const cancel = connection > 1 ? options.cancelConnection : undefined; + if (connection > 1) rawSocket.on("close", () => cancelConnectionClosed.resolve()); let buffered = Buffer.alloc(0); const onPlaintext = (data: Buffer) => { + const answered = buffered.length >= SSL_REQUEST.length; buffered = Buffer.concat([buffered, data]); if (buffered.length < SSL_REQUEST.length) return; + if (cancel === "declines-tls") { + // Keep everything the client sends in the clear after it was told N. + plaintext[connection - 1] = buffered; + if (!answered) rawSocket.write("N"); + return; + } plaintext[connection - 1] = buffered.subarray(0, SSL_REQUEST.length); // What follows the SSLRequest is the ClientHello: hand it to the TLS engine. rawSocket.removeListener("data", onPlaintext); @@ -103,7 +123,8 @@ async function backend(options: { tls?: boolean; host?: string; socketPath?: str const leftover = buffered.subarray(SSL_REQUEST.length); if (leftover.length) rawSocket.unshift(leftover); rawSocket.write("S"); - const secure = new tls.TLSSocket(rawSocket, { isServer: true, ...tlsCert }); + const certificate = cancel === "other-certificate" ? expiredTls : tlsCert; + const secure = new tls.TLSSocket(rawSocket, { isServer: true, ...certificate }); secure.on("error", () => {}); serve(connection, secure); }; @@ -117,9 +138,10 @@ async function backend(options: { tls?: boolean; host?: string; socketPath?: str socket.on("data", data => { buffered = Buffer.concat([buffered, data]); if (buffered.length < 16) return; + cancelPacketSeen = true; cancelPacket.resolve(buffered); // A real backend acts on the CancelRequest and hangs up. - if (!options.answersCancel) return void socket.end(); + if (options.cancelConnection !== "answers") return void socket.end(); socket.write(Buffer.concat([pgAuthenticationOk(), pgReadyForQuery()])); }); return; @@ -155,8 +177,11 @@ async function backend(options: { tls?: boolean; host?: string; socketPath?: str /** What each connection sent before TLS, by connection order. */ plaintext, cancelPacket: cancelPacket.promise, - /** Resolves once the connection that carried the CancelRequest is closed. */ + /** Resolves once the second connection is closed. */ cancelConnectionClosed: cancelConnectionClosed.promise, + get cancelPacketSeen() { + return cancelPacketSeen; + }, /** Resolves once the client has closed the connection its queries run on. */ queryConnectionClosed: queryConnectionClosed.promise, get connections() { @@ -269,6 +294,59 @@ test("cancel() on a TLS session sends the CancelRequest through TLS", async () = expect((await settled).errno).toBe("57014"); }); +// A session that is encrypted must not lose its cancel key to a cancel connection +// that is not. `prefer` counts once the session has negotiated TLS. +test.each(["prefer", "require"])( + "cancel() on a TLS session (sslmode=%s) sends nothing when TLS is declined", + async sslmode => { + await using server = await backend({ tls: true, cancelConnection: "declines-tls" }); + server.autoReply = false; + await using sql = new SQL({ url: `${server.url}?sslmode=${sslmode}`, max: 1, connectionTimeout: 5 }); + + const query = sql`select pg_sleep(10)`.execute(); + const settled = query.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + query.cancel(); + + await server.cancelConnectionClosed; + // The SSLRequest, then nothing: no CancelRequest after the N. + expect(server.plaintext[1]).toEqual(SSL_REQUEST); + + server.reply( + pgRowDescription([{ name: "v", typeOid: TEXT_OID }]), + pgCommandComplete("SELECT 0"), + pgReadyForQuery(), + ); + expect(await settled).toEqual([]); + }, +); + +test("cancel() on a verify-full session sends nothing to a server it cannot verify", async () => { + await using server = await backend({ tls: true, cancelConnection: "other-certificate" }); + server.autoReply = false; + await using sql = new SQL({ url: server.url, tls: { ca: tlsCert.cert }, max: 1, connectionTimeout: 5 }); + + const query = sql`select pg_sleep(10)`.execute(); + const settled = query.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + query.cancel(); + + await server.cancelConnectionClosed; + expect({ plaintext: server.plaintext[1], cancelPacketSeen: server.cancelPacketSeen }).toEqual({ + plaintext: SSL_REQUEST, + cancelPacketSeen: false, + }); + + server.reply(pgRowDescription([{ name: "v", typeOid: TEXT_OID }]), pgCommandComplete("SELECT 0"), pgReadyForQuery()); + expect(await settled).toEqual([]); +}); + // URL parsing keeps the brackets of an IPv6 literal in the hostname. The session's // connect strips them, so the cancel connection has to as well. test.skipIf(!isIPv6())("cancel() reaches a server that is addressed by an IPv6 literal", async () => { @@ -320,7 +398,7 @@ test.skipIf(isWindows)("cancel() reaches a server on a unix socket", async () => // The cancel connection carries one packet. It must not turn into a session, with // no timeout and no owner, because a server answers it. test("the cancel connection closes when the server answers it", async () => { - await using server = await backend({ answersCancel: true }); + await using server = await backend({ cancelConnection: "answers" }); server.autoReply = false; await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); From ec1eec7c42aa6b9f4ae3e29840c3f5ed2ec93141 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 25 Sep 2026 02:33:26 +0000 Subject: [PATCH 19/34] sql: shorten the send_cancel_request doc comment --- src/sql_jsc/postgres/PostgresSQLConnection.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index 78e9ec8be3a6..ab86715c40f8 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -1656,9 +1656,7 @@ impl PostgresSQLConnection { .is_some_and(|f| core::ptr::eq(f.as_ptr(), request)) } - /// Asks the server, from a second connection, to cancel what the backend of this - /// session runs. That connection goes where this one went, to the same peer address - /// or unix socket, and is encrypted when this one is. + /// Asks the server, on a second connection like this one, to cancel what this backend runs. pub(crate) fn send_cancel_request(&self) { let key = self.backend_key_data.get(); // No BackendKeyData was ever received, so the server cannot be asked. @@ -1670,6 +1668,7 @@ impl PostgresSQLConnection { return; }; + // The peer address, not the host name: the name can resolve to another server. let mut hostname = [0u8; 46]; let mut hostname_len = 0; let mut port = 0; From c0e36e3a8ac3111a97cd88549c33c07ae6525c4d Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 25 Sep 2026 02:43:00 +0000 Subject: [PATCH 20/34] sql(postgres): return the connect error from open and throw it in createConnection open is the native half of createConnection, so it reports a failed dial as the uws error it got. createConnection turns that into the same JS exception as before. --- src/sql_jsc/postgres/PostgresSQLConnection.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index f197ee9100b9..3e68f3d80c02 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -1198,6 +1198,12 @@ pub(crate) fn call(global_object: &JSGlobalObject, callframe: &CallFrame) -> JsR on_close: arguments[10], }, ) + .map_err(|err| { + global_object.throw_error( + bun_jsc::CrateError::from(err), + "failed to connect to postgresql", + ) + }) } /// What `PostgresSQLConnection::open` builds a connection from. @@ -1229,7 +1235,7 @@ impl PostgresSQLConnection { global_object: &JSGlobalObject, group: &mut bun_uws::SocketGroup, params: ConnectParams<'_>, - ) -> JsResult { + ) -> Result { let ConnectParams { hostname, port, @@ -1344,10 +1350,7 @@ impl PostgresSQLConnection { Err(err) => { // SAFETY: fresh allocation, sole ref. drop(unsafe { bun_core::heap::take(ptr) }); - return Err(global_object.throw_error( - bun_jsc::CrateError::from(err), - "failed to connect to postgresql", - )); + return Err(err); } })); } From 3ccf2dfbf98cc05f9cadba14059fcc353509a341 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 25 Sep 2026 02:43:25 +0000 Subject: [PATCH 21/34] sql: log a cancel connection that cannot be dialed open now reports a failed dial as a native error, so there is no exception to take and drop. --- src/sql_jsc/postgres/PostgresSQLConnection.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index 9ac399636d39..438e9cff34e1 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -1712,7 +1712,7 @@ impl PostgresSQLConnection { bun_jsc::rare_data::SocketGroups::of((*raw).group()) .postgres_group::(self.vm_mut().uws_loop()) }; - let opened = Self::open( + let dialed = Self::open( self.global(), group, ConnectParams { @@ -1745,8 +1745,8 @@ impl PostgresSQLConnection { }, ); // Best effort: a cancel that cannot be dialed leaves the query running. - if opened.is_err() { - let _ = self.global().try_take_exception(); + if let Err(err) = dialed { + debug!("cancel request not dialed: {:?}", err); } } From c2b627f78e0b34d8fd8e92dd5171eeee988ef342 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 25 Sep 2026 02:50:44 +0000 Subject: [PATCH 22/34] sql(postgres): build the strings of a connection in one constructor ConnectParams carried the buffer and the five slices into it as separate public fields, so a second caller could pass slices that point elsewhere. ConnectionStrings::new is now the only way to make them. createConnection checks its arguments for null bytes before it copies them, not after. --- src/sql_jsc/postgres/PostgresSQLConnection.rs | 151 ++++++++---------- 1 file changed, 69 insertions(+), 82 deletions(-) diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index 3e68f3d80c02..092c1edcc01f 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -1102,71 +1102,26 @@ pub(crate) fn call(global_object: &JSGlobalObject, callframe: &CallFrame) -> JsR }; let (secure, tls_config) = (args.secure, args.tls_config); - // `StringBuilder::append` takes `&mut self` and returns a borrow - // of the backing buffer, so successive appends can't keep their `&[u8]` - // results live across each other. The buffer is allocated once and never - // moved (`move_to_slice` hands back the same allocation), so detach each - // result to a `RawSlice` immediately — the struct stores them as - // `RawSlice` (self-referential into `options_buf`). - let username: bun_ptr::RawSlice; - let password: bun_ptr::RawSlice; - let database: bun_ptr::RawSlice; - let options: bun_ptr::RawSlice; - let path: bun_ptr::RawSlice; - let options_str = arguments[7].to_bun_string(global_object)?; - let path_str = arguments[8].to_bun_string(global_object)?; - - let options_buf: Box<[u8]> = 'brk: { - let mut b = bun_core::StringBuilder::default(); - b.cap += args.username_str.utf8_byte_length() - + 1 - + args.password_str.utf8_byte_length() - + 1 - + args.database_str.utf8_byte_length() - + 1 - + options_str.utf8_byte_length() - + 1 - + path_str.utf8_byte_length() - + 1; - - let _ = b.allocate(); - let u = args.username_str.to_utf8(); - username = bun_ptr::RawSlice::new(b.append(u.slice())); - drop(u); - - let p = args.password_str.to_utf8(); - password = bun_ptr::RawSlice::new(b.append(p.slice())); - drop(p); - - let d = args.database_str.to_utf8(); - database = bun_ptr::RawSlice::new(b.append(d.slice())); - drop(d); - - let o = options_str.to_utf8(); - options = bun_ptr::RawSlice::new(b.append(o.slice())); - drop(o); - - let _path = path_str.to_utf8(); - path = bun_ptr::RawSlice::new(b.append(_path.slice())); - drop(_path); - - break 'brk b.move_to_slice(); - }; + let (username, password, database, options, path) = ( + args.username_str.to_utf8(), + args.password_str.to_utf8(), + args.database_str.to_utf8(), + options_str.to_utf8(), + path_str.to_utf8(), + ); // Reject null bytes in connection parameters to prevent Postgres startup // message parameter injection (null bytes act as field terminators in the // wire protocol's key\0value\0 format). for (entry, name) in [ - (username, &b"username"[..]), - (password, b"password"), - (database, b"database"), - (path, b"path"), + (username.slice(), &b"username"[..]), + (password.slice(), b"password"), + (database.slice(), b"database"), + (path.slice(), b"path"), ] { - let entry = entry.slice(); if !entry.is_empty() && strings::contains_char(entry, 0) { - drop(options_buf); return Err(global_object.throw_invalid_arguments(format_args!( "{} must not contain null bytes", bstr::BStr::new(name) @@ -1181,12 +1136,13 @@ pub(crate) fn call(global_object: &JSGlobalObject, callframe: &CallFrame) -> JsR ConnectParams { hostname: hostname.slice(), port: args.port, - options_buf, - user: username, - password, - database, - options, - path, + strings: ConnectionStrings::new( + username.slice(), + password.slice(), + database.slice(), + options.slice(), + path.slice(), + ), secure, tls_config, ssl_mode: args.ssl_mode, @@ -1206,18 +1162,50 @@ pub(crate) fn call(global_object: &JSGlobalObject, callframe: &CallFrame) -> JsR }) } +/// The strings of a connection, in one buffer that moves into the connection with them. +pub(crate) struct ConnectionStrings { + buf: Box<[u8]>, + user: bun_ptr::RawSlice, + password: bun_ptr::RawSlice, + database: bun_ptr::RawSlice, + options: bun_ptr::RawSlice, + path: bun_ptr::RawSlice, +} + +impl ConnectionStrings { + pub(crate) fn new( + user: &[u8], + password: &[u8], + database: &[u8], + options: &[u8], + path: &[u8], + ) -> Self { + let mut b = bun_core::StringBuilder::default(); + b.cap += user.len() + password.len() + database.len() + options.len() + path.len() + 5; + let _ = b.allocate(); + // The buffer never moves again, so each slice can outlive the borrow of `b`. + let user = bun_ptr::RawSlice::new(b.append(user)); + let password = bun_ptr::RawSlice::new(b.append(password)); + let database = bun_ptr::RawSlice::new(b.append(database)); + let options = bun_ptr::RawSlice::new(b.append(options)); + let path = bun_ptr::RawSlice::new(b.append(path)); + Self { + buf: b.move_to_slice(), + user, + password, + database, + options, + path, + } + } +} + /// What `PostgresSQLConnection::open` builds a connection from. pub(crate) struct ConnectParams<'a> { - /// Dialed when `path` is empty. + /// Dialed when the path of `strings` is empty. pub hostname: &'a [u8], pub port: i32, - /// The five slices below point into it. - pub options_buf: Box<[u8]>, - pub user: bun_ptr::RawSlice, - pub password: bun_ptr::RawSlice, - pub database: bun_ptr::RawSlice, - pub options: bun_ptr::RawSlice, - pub path: bun_ptr::RawSlice, + pub strings: ConnectionStrings, pub secure: Option, pub tls_config: jsc::api::ServerConfig::SSLConfig, pub ssl_mode: SSLMode, @@ -1239,12 +1227,15 @@ impl PostgresSQLConnection { let ConnectParams { hostname, port, - options_buf, - user: username, - password, - database, - options, - path, + strings: + ConnectionStrings { + buf: options_buf, + user: username, + password, + database, + options, + path, + }, secure, tls_config, ssl_mode, @@ -1314,15 +1305,11 @@ impl PostgresSQLConnection { channel_names: JsCell::new(Vec::new()), })); - // `heap::into_raw` is `Box::into_raw` — never null. Sole owner until - // `to_js` below. R-2: every field is interior-mutable, so a shared - // `ParentRef` deref is sufficient for the writes below. + // Sole owner until `to_js` below. Every field is interior-mutable. let this = ParentRef::from(core::ptr::NonNull::new(ptr).expect("heap::into_raw non-null")); { - // Postgres always opens plain TCP first (SSLRequest happens in-band), - // so even `ssl_mode != .disable` lands in the TCP group; `setupTLS()` - // adopts into `postgres_tls_group` after the server's `S`. + // Plain TCP in every sslmode: `setup_tls` adopts the socket after the server's `S`. let path_slice = this.path.slice(); let result = if !path_slice.is_empty() { uws::SocketTCP::connect_unix_group( From 998a6faec4aaf67402d17fe78e1ad6988d951122 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 25 Sep 2026 03:01:44 +0000 Subject: [PATCH 23/34] sql(postgres): name the functions that build and store the connection strings The two comments on the string slices of PostgresSQLConnection still said that createConnection builds them. ConnectionStrings::new builds them and open stores them. --- 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 092c1edcc01f..7571aead6241 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -139,7 +139,7 @@ pub struct PostgresSQLConnection { pub(crate) backend_parameters: JsCell, // Self-referential — `database`/`user`/`password`/`path`/`options` are slices - // into `options_buf` (built via StringBuilder in `call`). Struct is Box-allocated + // into `options_buf` (built by `ConnectionStrings::new`). Struct is Box-allocated // and never moves (intrusive refcount), so the `RawSlice` backing-outlives-holder // invariant holds. Private — reassigning `options_buf` is UAF. // Reach via `database()`/`user()`/`password()`/`path()`/`options()`. @@ -267,9 +267,7 @@ impl PostgresSQLConnection { // ---- self-referential connection-string slices ---------------------------- // `database`/`user`/`password`/`path`/`options` are raw `*const [u8]` fat - // pointers into `self.options_buf`. They are populated once in `call()` (each - // initialised to `b""` then re-pointed at the StringBuilder allocation that - // becomes `options_buf`) and never reassigned. The struct is Box-allocated + // pointers into `self.options_buf`. `open` sets them once. The struct is Box-allocated // via `heap::alloc` and freed only when the intrusive refcount hits zero, // so `options_buf` — and thus every slice — remains valid for any `&self`. // From 819cd9ce6b09e6a577a90cf0b41fa6ed79682ad7 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 25 Sep 2026 03:12:17 +0000 Subject: [PATCH 24/34] sql(postgres): write the terminators of the connection strings ConnectionStrings::new reserved one byte more than each string needs, as createConnection did before, but no append wrote that byte. The buffer ended with 5 bytes that were never written. Count and append each string with its terminator, so that every byte of the buffer is written. --- src/sql_jsc/postgres/PostgresSQLConnection.rs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index 7571aead6241..8f025339625f 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -1179,14 +1179,16 @@ impl ConnectionStrings { path: &[u8], ) -> Self { let mut b = bun_core::StringBuilder::default(); - b.cap += user.len() + password.len() + database.len() + options.len() + path.len() + 5; + for string in [user, password, database, options, path] { + b.count_z(string); + } let _ = b.allocate(); // The buffer never moves again, so each slice can outlive the borrow of `b`. - let user = bun_ptr::RawSlice::new(b.append(user)); - let password = bun_ptr::RawSlice::new(b.append(password)); - let database = bun_ptr::RawSlice::new(b.append(database)); - let options = bun_ptr::RawSlice::new(b.append(options)); - let path = bun_ptr::RawSlice::new(b.append(path)); + let user = bun_ptr::RawSlice::new(b.append_z(user).as_bytes()); + let password = bun_ptr::RawSlice::new(b.append_z(password).as_bytes()); + let database = bun_ptr::RawSlice::new(b.append_z(database).as_bytes()); + let options = bun_ptr::RawSlice::new(b.append_z(options).as_bytes()); + let path = bun_ptr::RawSlice::new(b.append_z(path).as_bytes()); Self { buf: b.move_to_slice(), user, From df941a081176198b777011a86fcde470323cfa33 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 25 Sep 2026 03:57:41 +0000 Subject: [PATCH 25/34] sql(postgres): let the process exit after a dial that never opens, and keep a statement whose Parse was cancelled A dial to an IP literal is a socket before it is open. uSockets reports nothing when the application closes such a socket, so ref_and_close now releases the event loop itself and drops the socket pointer. Before, a connection timeout during the dial left the process running for good. The cancel connection always dials an IP literal. A session does when its host is one. An ErrorResponse with SQLSTATE 57014 that arrives while a statement is in Parse no longer fails the statement. The error belongs to the query that was cancelled. A query with the same text that waits behind it parses the statement again. The cancel connection ends within the connection timeout of its session when that is shorter than 5 s. --- src/sql/postgres/protocol/ErrorResponse.rs | 7 ++ src/sql_jsc/postgres/PostgresSQLConnection.rs | 26 +++- test/js/sql/postgres-pending-dial-fixture.ts | 112 ++++++++++++++++++ test/js/sql/postgres-query-cancel.test.ts | 57 ++++++++- .../sql/sql-connect-error-reporting.test.ts | 21 ++++ 5 files changed, 217 insertions(+), 6 deletions(-) create mode 100644 test/js/sql/postgres-pending-dial-fixture.ts diff --git a/src/sql/postgres/protocol/ErrorResponse.rs b/src/sql/postgres/protocol/ErrorResponse.rs index 1181f8437a8e..a179e0f4b9d7 100644 --- a/src/sql/postgres/protocol/ErrorResponse.rs +++ b/src/sql/postgres/protocol/ErrorResponse.rs @@ -30,6 +30,13 @@ impl ErrorResponse { } Ok(Self::default()) } + + /// SQLSTATE 57014: a cancel request or a timeout stopped the query. + pub fn is_query_canceled(&self) -> bool { + self.messages + .iter() + .any(|message| matches!(message, FieldMessage::Code(code) if code.eq_ascii(b"57014"))) + } } // `to_js` lives on an extension trait in the `bun_sql_jsc` crate. diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index 4091812ec1a0..671233b53957 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -52,7 +52,7 @@ pub use bun_sql::postgres::TLSStatus as TlsStatus; type Socket = uws::AnySocket; -/// From dial to hang-up, for the connection that delivers a CancelRequest. +/// The longest that the connection that delivers a CancelRequest lives, from dial to hang-up. const CANCEL_REQUEST_TIMEOUT_MS: i32 = 5_000; bun_core::define_scoped_log!(debug, Postgres, visible); @@ -1600,16 +1600,24 @@ impl PostgresSQLConnection { fn ref_and_close(&self, js_reason: Option) { // refAndClose is always called when we wanna to disconnect or when we are closed - if !self.socket.get().is_closed() { + let socket = self.socket.get(); + if !socket.is_closed() { + let opened = socket.is_established(); // event loop need to be alive to close the socket self.poll_ref.with_mut(|r| r.ref_(self.vm_ctx())); // will unref on socket close - self.socket.get().close(if self.is_cancel_request() { + socket.close(if self.is_cancel_request() { // Not `Normal`: on TLS that waits for the peer's close_notify. uws::CloseKind::Failure } else { uws::CloseKind::Normal }); + if !opened { + // uSockets closes a socket that never opened with no event, so this is its `on_close`. + self.socket + .set(Socket::SocketTcp(uws::SocketTCP::detached())); + self.poll_ref.with_mut(|r| r.unref(self.vm_ctx())); + } } // cleanup requests @@ -1693,6 +1701,11 @@ impl PostgresSQLConnection { bun_jsc::rare_data::SocketGroups::of((*raw).group()) .postgres_group::(self.vm_mut().uws_loop()) }; + // The connection timeout of this session when that is the shorter one. + let connection_timeout = match i32::try_from(self.connection_timeout_ms) { + Ok(session @ 1..) => session.min(CANCEL_REQUEST_TIMEOUT_MS), + _ => CANCEL_REQUEST_TIMEOUT_MS, + }; let dialed = Self::open( self.global(), group, @@ -1709,7 +1722,7 @@ impl PostgresSQLConnection { _ => SSLMode::Disable, }, idle_timeout: 0, - connection_timeout: CANCEL_REQUEST_TIMEOUT_MS, + connection_timeout, max_lifetime: 0, use_unnamed_prepared_statements: false, on_connect: JSValue::ZERO, @@ -3205,7 +3218,10 @@ impl PostgresSQLConnection { let js_err = crate::postgres::protocol::error_response_jsc::to_js(&err, self.global()); if let Some(stmt) = request.statement_mut() { - if stmt.status == StatementStatus::Parsing { + if stmt.status == StatementStatus::Parsing && err.is_query_canceled() { + // A canceled Parse says nothing about the statement: the next request parses it again. + stmt.status = StatementStatus::Pending; + } else if stmt.status == StatementStatus::Parsing { stmt.status = StatementStatus::Failed; stmt.error_response = Some( crate::postgres::postgres_sql_statement::Error::Protocol(err), diff --git a/test/js/sql/postgres-pending-dial-fixture.ts b/test/js/sql/postgres-pending-dial-fixture.ts new file mode 100644 index 000000000000..064a75b69eb0 --- /dev/null +++ b/test/js/sql/postgres-pending-dial-fixture.ts @@ -0,0 +1,112 @@ +// A dial to an IP literal is a socket from its first moment, and uSockets reports +// nothing when the application closes such a socket before it opens. Each mode +// leaves the process with one dial that never completes, and the process has to +// exit on its own once that dial times out. +// +// connect the dial of the session itself +// cancel the dial of the connection that cancel() opens for a running query +// +// The listener is a raw libc socket. Its backlog holds one connection, which no +// listener of Bun can ask for, and nothing accepts from it unless this file does. +// With the backlog full the kernel drops every SYN. +import { SQL } from "bun"; +import { dlopen, ptr } from "bun:ffi"; +import net from "node:net"; +import { pgAuthenticationOk, pgBackendKeyData, pgReadyForQuery } from "./wire-frames"; + +const darwin = process.platform === "darwin"; +const libc = dlopen(darwin ? "libSystem.B.dylib" : "libc.so.6", { + socket: { args: ["int", "int", "int"], returns: "int" }, + bind: { args: ["int", "ptr", "int"], returns: "int" }, + listen: { args: ["int", "int"], returns: "int" }, + getsockname: { args: ["int", "ptr", "ptr"], returns: "int" }, + accept: { args: ["int", "ptr", "ptr"], returns: "int" }, + poll: { args: ["ptr", "u64", "int"], returns: "int" }, + read: { args: ["int", "ptr", "usize"], returns: "int" }, + write: { args: ["int", "ptr", "usize"], returns: "int" }, + close: { args: ["int"], returns: "int" }, +}).symbols; + +const AF_INET = 2; +const SOCK_STREAM = 1; +const POLLIN = 1; + +const address = new Uint8Array(16); +if (darwin) { + address[0] = 16; + address[1] = AF_INET; +} else { + new DataView(address.buffer).setUint16(0, AF_INET, true); +} +address.set([127, 0, 0, 1], 4); +const listener = libc.socket(AF_INET, SOCK_STREAM, 0); +// The smallest backlog that admits one connection: macOS reads 0 as no limit. +if (listener < 0 || libc.bind(listener, ptr(address), 16) !== 0 || libc.listen(listener, darwin ? 1 : 0) !== 0) { + throw new Error("listen failed"); +} +if (libc.getsockname(listener, ptr(address), ptr(new Uint32Array([16]))) !== 0) { + throw new Error("getsockname failed"); +} +const port = (address[2] << 8) | address[3]; +const url = `postgres://postgres@127.0.0.1:${port}/postgres?sslmode=disable`; + +/** Resolves once a read of `fd`, or an accept from it, does not block. */ +async function readable(fd: number) { + const pollfd = new DataView(new ArrayBuffer(8)); + pollfd.setInt32(0, fd, true); + pollfd.setInt16(4, POLLIN, true); + while (libc.poll(ptr(pollfd), 1, 0) === 0) await new Promise(resolve => setImmediate(resolve)); +} + +/** From here on the kernel answers no SYN for `port`. */ +async function fillBacklog() { + const filler = net.connect(port, "127.0.0.1"); + await new Promise((resolve, reject) => filler.on("connect", resolve).on("error", reject)); + return filler; +} + +const code = (query: Promise) => + query.then( + () => "resolved", + err => err.code, + ); + +if (process.argv[2] === "connect") { + const filler = await fillBacklog(); + const sql = new SQL({ url, max: 1, connectionTimeout: 1 }); + console.log(await code(sql`select 1`)); + filler.destroy(); +} else { + const sql = new SQL({ url, max: 1, connectionTimeout: 1 }); + const query = sql`select pg_sleep(10)`.simple(); + const settled = code(query); + + await readable(listener); + const session = libc.accept(listener, null, null); + if (session < 0) throw new Error("accept failed"); + const handshake = Buffer.concat([pgAuthenticationOk(), pgBackendKeyData(4242, 13371337), pgReadyForQuery()]); + if (libc.write(session, ptr(handshake), handshake.length) !== handshake.length) throw new Error("write failed"); + + // The startup message, then the query: Byte1('Q') Int32(length) String. With + // the whole query read, the query is the one the backend runs. + const received = Buffer.alloc(4096); + let length = 0; + const queryReceived = () => { + if (length < 4) return false; + const query = received.readUInt32BE(0); + return length >= query + 5 && length >= query + 1 + received.readUInt32BE(query + 1); + }; + while (!queryReceived()) { + await readable(session); + const read = libc.read(session, ptr(received, length), received.length - length); + if (read <= 0) throw new Error("the client closed the session"); + length += read; + } + + const filler = await fillBacklog(); + query.cancel(); + // The backend goes away. The cancel connection is still in its dial. + libc.close(session); + console.log(await settled); + filler.destroy(); +} diff --git a/test/js/sql/postgres-query-cancel.test.ts b/test/js/sql/postgres-query-cancel.test.ts index d4c4f66563e0..f87660433e89 100644 --- a/test/js/sql/postgres-query-cancel.test.ts +++ b/test/js/sql/postgres-query-cancel.test.ts @@ -10,7 +10,7 @@ // cancelled before it was dispatched never settled at all. import { SQL } from "bun"; import { expect, test } from "bun:test"; -import { expiredTls, isIPv6, isWindows, tempDir, tls as tlsCert } from "harness"; +import { bunEnv, bunExe, expiredTls, isIPv6, isMusl, isWindows, tempDir, tls as tlsCert } from "harness"; import net from "node:net"; import { join } from "node:path"; import tls from "node:tls"; @@ -420,6 +420,61 @@ test("the cancel connection closes when the server answers it", async () => { expect((await settled).errno).toBe("57014"); }); +// A dial to an IP literal is a socket before it is open, and uSockets reports +// nothing when the timeout of the cancel connection closes it. The connection +// has to release the event loop itself, or the process never exits. +test.skipIf(isWindows || isMusl)( + "the process exits when the dial of the cancel connection never completes", + async () => { + await using proc = Bun.spawn({ + cmd: [bunExe(), join(import.meta.dir, "postgres-pending-dial-fixture.ts"), "cancel"], + env: bunEnv, + stdout: "pipe", + stderr: "inherit", + }); + const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); + expect(stdout).toBe("ERR_POSTGRES_CONNECTION_CLOSED\n"); + expect(exitCode).toBe(0); + }, + 30_000, +); + +// The first run of a statement sends its Parse together with the Bind and the +// Execute. A backend that waits for a lock waits inside that Parse, so the error +// of a cancel arrives with no ParseComplete before it. That error belongs to the +// cancelled query. A query with the same text that waits behind it shares the +// statement and has to parse it again. +test("cancel() during the Parse of a statement does not fail the queries that share it", async () => { + await using server = await backend(); + server.autoReply = false; + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + + const cancelled = sql`select 'shared'`.execute(); + const cancelledSettled = cancelled.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + const waiting = sql`select 'shared'`.execute(); + const waitingSettled = waiting.then( + rows => rows, + err => err, + ); + + cancelled.cancel(); + expect(await server.cancelPacket).toEqual(pgCancelRequest(PROCESS_ID, SECRET_KEY)); + server.autoReply = true; + server.reply( + pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), + pgReadyForQuery(), + ); + + expect((await cancelledSettled).errno).toBe("57014"); + expect(await waitingSettled).toEqual([{ v: "ok" }]); + // The second unit is the Parse, Bind and Execute of the waiting query. + expect(server.queryUnits).toBe(2); +}); + test("cancel() before the query is dispatched rejects it instead of hanging", async () => { await using server = await backend(); await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); diff --git a/test/js/sql/sql-connect-error-reporting.test.ts b/test/js/sql/sql-connect-error-reporting.test.ts index 95b22a54264d..913e6e0ac58c 100644 --- a/test/js/sql/sql-connect-error-reporting.test.ts +++ b/test/js/sql/sql-connect-error-reporting.test.ts @@ -24,7 +24,9 @@ import { SQL } from "bun"; import { expect, mock, test } from "bun:test"; +import { bunEnv, bunExe, isMusl, isWindows } from "harness"; import type net from "node:net"; +import { join } from "node:path"; import { closedPort, listeningServer, @@ -284,6 +286,25 @@ test("postgres: connectionTimeout: 0 disables connect retries", async () => { } }); +// A dial to an IP literal is a socket before it is open, and uSockets reports +// nothing when the connection timeout closes it. The connection has to release +// the event loop itself, or the process never exits. +test.skipIf(isWindows || isMusl)( + "postgres: the process exits after a connection timeout on a dial that never completes", + async () => { + await using proc = Bun.spawn({ + cmd: [bunExe(), join(import.meta.dir, "postgres-pending-dial-fixture.ts"), "connect"], + env: bunEnv, + stdout: "pipe", + stderr: "inherit", + }); + const [stdout, exitCode] = await Promise.all([proc.stdout.text(), proc.exited]); + expect(stdout).toBe("ERR_POSTGRES_CONNECTION_TIMEOUT\n"); + expect(exitCode).toBe(0); + }, + 30_000, +); + test("mysql: graceful close() resolves while a connect retry is pending", async () => { const firstConnection = Promise.withResolvers(); const { port, server } = await listeningServer(socket => { From 3b664c69fdb52f801463143fe622e9f2c7e455aa Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 25 Sep 2026 03:57:42 +0000 Subject: [PATCH 26/34] docs(sql): say that a late cancel request can stop the next query --- docs/runtime/sql.mdx | 2 +- packages/bun-types/sql.d.ts | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/runtime/sql.mdx b/docs/runtime/sql.mdx index 0d0044291750..56c702373cb5 100644 --- a/docs/runtime/sql.mdx +++ b/docs/runtime/sql.mdx @@ -482,7 +482,7 @@ await query; On PostgreSQL, what `cancel()` does depends on how far the query got: - A query that Bun has not sent yet never runs. It rejects with `ERR_POSTGRES_QUERY_CANCELLED`. -- A query that the server is running can only be stopped from a separate connection. Bun opens one to the same server, encrypted when the session is, and sends a `CancelRequest` on it. This is a request. If the server stops the query, the query rejects with SQLSTATE `57014`. If the query finishes first, it resolves as usual. +- A query that the server is running can only be stopped from a separate connection. Bun opens one to the same server, encrypted when the session is, and sends a `CancelRequest` on it. This is a request. If the server stops the query, the query rejects with SQLSTATE `57014`. If the query finishes first, it resolves as usual, and the request can stop the next query on that connection instead. - A query that Bun already sent behind another query on the same connection also rejects with `ERR_POSTGRES_QUERY_CANCELLED`, but the server still runs it. The `hint` of the error says so. An `INSERT` or `UPDATE` in such a query still takes effect, so do not retry it blindly. --- diff --git a/packages/bun-types/sql.d.ts b/packages/bun-types/sql.d.ts index 37d0d6142e94..ac7104294f14 100644 --- a/packages/bun-types/sql.d.ts +++ b/packages/bun-types/sql.d.ts @@ -473,7 +473,8 @@ declare module "bun" { * For PostgreSQL, a query the server is running is cancelled with a * `CancelRequest` on a second connection. If the server stops the query, it * rejects with SQLSTATE 57014. If the query finishes first, it resolves as - * usual. A query that was already sent behind another query rejects with + * usual, and the request can stop the next query on that connection + * instead. A query that was already sent behind another query rejects with * `ERR_POSTGRES_QUERY_CANCELLED` and a `hint`, but the server still runs it. */ cancel(): Query; From e8b81f9383c6108aa26c821213a4264241558c0e Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 25 Sep 2026 04:25:55 +0000 Subject: [PATCH 27/34] test(sql): check that the cancel connection verifies the host name of the session The cancel connection dials the address of the peer. The certificate of the new test names only localhost, so a check against the dialed address would refuse it. Remove the timeout argument of the two tests that run the pending dial fixture. The connect mode of the fixture now uses a connection timeout of 0.2 s, because nothing has to succeed within it. The docs say that the server ignores a cancel request that arrives before its query. --- docs/runtime/sql.mdx | 2 +- packages/bun-types/sql.d.ts | 3 +- test/js/sql/postgres-pending-dial-fixture.ts | 3 +- test/js/sql/postgres-query-cancel.test.ts | 45 ++++++++++++++++++- .../sql/sql-connect-error-reporting.test.ts | 1 - 5 files changed, 48 insertions(+), 6 deletions(-) diff --git a/docs/runtime/sql.mdx b/docs/runtime/sql.mdx index 56c702373cb5..356d88b17290 100644 --- a/docs/runtime/sql.mdx +++ b/docs/runtime/sql.mdx @@ -482,7 +482,7 @@ await query; On PostgreSQL, what `cancel()` does depends on how far the query got: - A query that Bun has not sent yet never runs. It rejects with `ERR_POSTGRES_QUERY_CANCELLED`. -- A query that the server is running can only be stopped from a separate connection. Bun opens one to the same server, encrypted when the session is, and sends a `CancelRequest` on it. This is a request. If the server stops the query, the query rejects with SQLSTATE `57014`. If the query finishes first, it resolves as usual, and the request can stop the next query on that connection instead. +- A query that the server is running can only be stopped from a separate connection. Bun opens one to the same server, encrypted when the session is, and sends a `CancelRequest` on it. This is a request. If the server stops the query, the query rejects with SQLSTATE `57014`. If the query finishes first, it resolves as usual, and the request can stop the next query on that connection instead. The server also ignores a request that arrives before the query does, which can happen when you cancel a query with megabytes of parameters at once. - A query that Bun already sent behind another query on the same connection also rejects with `ERR_POSTGRES_QUERY_CANCELLED`, but the server still runs it. The `hint` of the error says so. An `INSERT` or `UPDATE` in such a query still takes effect, so do not retry it blindly. --- diff --git a/packages/bun-types/sql.d.ts b/packages/bun-types/sql.d.ts index ac7104294f14..a9a9b2543430 100644 --- a/packages/bun-types/sql.d.ts +++ b/packages/bun-types/sql.d.ts @@ -474,7 +474,8 @@ declare module "bun" { * `CancelRequest` on a second connection. If the server stops the query, it * rejects with SQLSTATE 57014. If the query finishes first, it resolves as * usual, and the request can stop the next query on that connection - * instead. A query that was already sent behind another query rejects with + * instead. The server ignores a request that arrives before the query + * does. A query that was already sent behind another query rejects with * `ERR_POSTGRES_QUERY_CANCELLED` and a `hint`, but the server still runs it. */ cancel(): Query; diff --git a/test/js/sql/postgres-pending-dial-fixture.ts b/test/js/sql/postgres-pending-dial-fixture.ts index 064a75b69eb0..335f353b2dd8 100644 --- a/test/js/sql/postgres-pending-dial-fixture.ts +++ b/test/js/sql/postgres-pending-dial-fixture.ts @@ -73,7 +73,8 @@ const code = (query: Promise) => if (process.argv[2] === "connect") { const filler = await fillBacklog(); - const sql = new SQL({ url, max: 1, connectionTimeout: 1 }); + // Nothing has to succeed within the timeout, so it can be short. + const sql = new SQL({ url, max: 1, connectionTimeout: 0.2 }); console.log(await code(sql`select 1`)); filler.destroy(); } else { diff --git a/test/js/sql/postgres-query-cancel.test.ts b/test/js/sql/postgres-query-cancel.test.ts index f87660433e89..78d4343110c4 100644 --- a/test/js/sql/postgres-query-cancel.test.ts +++ b/test/js/sql/postgres-query-cancel.test.ts @@ -11,6 +11,7 @@ import { SQL } from "bun"; import { expect, test } from "bun:test"; import { bunEnv, bunExe, expiredTls, isIPv6, isMusl, isWindows, tempDir, tls as tlsCert } from "harness"; +import { readFileSync } from "node:fs"; import net from "node:net"; import { join } from "node:path"; import tls from "node:tls"; @@ -36,6 +37,12 @@ const SECRET_KEY = 13371337; // has already prepared). const TEXT_OID = 25; +// A certificate that names `localhost` and no address: both of its names are DNS entries. +const hostNameOnlyTls = { + cert: readFileSync(join(import.meta.dir, "docker-tls", "server.crt"), "utf8"), + key: readFileSync(join(import.meta.dir, "docker-tls", "server.key"), "utf8"), +}; + // Int32(8) Int32(80877103): the one message a client sends in plaintext before TLS. const SSL_REQUEST = Buffer.from([0, 0, 0, 8, 0x04, 0xd2, 0x16, 0x2f]); @@ -59,6 +66,7 @@ const SSL_REQUEST = Buffer.from([0, 0, 0, 8, 0x04, 0xd2, 0x16, 0x2f]); async function backend( options: { tls?: boolean; + certificate?: { cert: string; key: string }; host?: string; socketPath?: string; cancelConnection?: "answers" | "declines-tls" | "other-certificate"; @@ -123,7 +131,7 @@ async function backend( const leftover = buffered.subarray(SSL_REQUEST.length); if (leftover.length) rawSocket.unshift(leftover); rawSocket.write("S"); - const certificate = cancel === "other-certificate" ? expiredTls : tlsCert; + const certificate = cancel === "other-certificate" ? expiredTls : (options.certificate ?? tlsCert); const secure = new tls.TLSSocket(rawSocket, { isServer: true, ...certificate }); secure.on("error", () => {}); serve(connection, secure); @@ -347,6 +355,40 @@ test("cancel() on a verify-full session sends nothing to a server it cannot veri expect(await settled).toEqual([]); }); +// The cancel connection dials the address of the session's peer, not its host +// name. The certificate still has to match the host name. This one names only +// `localhost`, so a check against the dialed address refuses it, as the session +// that is addressed by 127.0.0.1 shows. +test("cancel() on a verify-full session checks the certificate against the host name", async () => { + const tls = { ca: hostNameOnlyTls.cert }; + { + await using byAddress = await backend({ tls: true, certificate: hostNameOnlyTls }); + await using sql = new SQL({ url: byAddress.url, tls, max: 1, connectionTimeout: 5 }); + const err = await sql`select 1`.catch((e: any) => e); + expect(err.message).toBe("Hostname/IP does not match certificate's altnames"); + } + + await using server = await backend({ tls: true, certificate: hostNameOnlyTls, host: "localhost" }); + server.autoReply = false; + await using sql = new SQL({ url: server.url, tls, max: 1, connectionTimeout: 5 }); + + const query = sql`select pg_sleep(10)`.execute(); + const settled = query.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + query.cancel(); + + expect(await server.cancelPacket).toEqual(pgCancelRequest(PROCESS_ID, SECRET_KEY)); + + server.reply( + pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), + pgReadyForQuery(), + ); + expect((await settled).errno).toBe("57014"); +}); + // URL parsing keeps the brackets of an IPv6 literal in the hostname. The session's // connect strips them, so the cancel connection has to as well. test.skipIf(!isIPv6())("cancel() reaches a server that is addressed by an IPv6 literal", async () => { @@ -436,7 +478,6 @@ test.skipIf(isWindows || isMusl)( expect(stdout).toBe("ERR_POSTGRES_CONNECTION_CLOSED\n"); expect(exitCode).toBe(0); }, - 30_000, ); // The first run of a statement sends its Parse together with the Bind and the diff --git a/test/js/sql/sql-connect-error-reporting.test.ts b/test/js/sql/sql-connect-error-reporting.test.ts index 913e6e0ac58c..7958ef142966 100644 --- a/test/js/sql/sql-connect-error-reporting.test.ts +++ b/test/js/sql/sql-connect-error-reporting.test.ts @@ -302,7 +302,6 @@ test.skipIf(isWindows || isMusl)( expect(stdout).toBe("ERR_POSTGRES_CONNECTION_TIMEOUT\n"); expect(exitCode).toBe(0); }, - 30_000, ); test("mysql: graceful close() resolves while a connect retry is pending", async () => { From 76a436ef4c0098fabbc4e2a3cc378f233afeefdc Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 30 Sep 2026 04:20:54 +0000 Subject: [PATCH 28/34] sql(postgres): send no CancelRequest for a query that ended during the dial The cancel connection now holds the query that it stops. When it is ready to write, it looks at the query again: the packet goes out only while the query is still the head of its session and the backend has not finished it. Before, a query that ended during the TCP and TLS handshake of the cancel connection left a CancelRequest that stopped the next query of that backend. The cancel connection reads the cancel key from the session at that time and no longer keeps a copy. Tests: a cancel connection whose SSLRequest the server answers only after the query ended sends nothing, and cancel() stops a query on a real PostgreSQL server. --- src/sql_jsc/postgres/PostgresSQLConnection.rs | 46 ++++++--- src/sql_jsc/postgres/PostgresSQLQuery.rs | 2 +- test/js/sql/postgres-query-cancel.test.ts | 99 +++++++++++++++++-- 3 files changed, 126 insertions(+), 21 deletions(-) diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index 8c861617e460..7442da45c4c6 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -141,6 +141,8 @@ pub struct PostgresSQLConnection { pub(crate) backend_parameters: JsCell, pub(crate) backend_key_data: JsCell, + /// The query that a cancel connection stops, until it writes the CancelRequest. + cancel_target: JsCell>>, // Self-referential — `database`/`user`/`password`/`path`/`options` are slices // into `options_buf` (built by `ConnectionStrings::new`). Struct is Box-allocated @@ -845,7 +847,12 @@ impl PostgresSQLConnection { debug!("sendStartupMessage"); self.status.set(Status::SentStartupMessage); if self.is_cancel_request() { - let packet = self.backend_key_data.get().cancel_request(); + let target = self.cancel_target.with_mut(Option::take); + // The query can end during the dial, and a CancelRequest then stops the next query. + let Some(packet) = target.and_then(|request| Self::cancel_request_for(&request)) else { + self.fail(b"Connection closed", AnyPostgresError::ConnectionClosed); + return; + }; if let Err(err) = self.writer().write(&packet) { self.fail(b"Failed to write cancel request", err); } @@ -1234,8 +1241,8 @@ pub(crate) struct ConnectParams<'a> { pub use_unnamed_prepared_statements: bool, pub on_connect: JSValue, pub on_close: JSValue, - /// Set for a connection that only delivers a CancelRequest for this backend. - pub cancel: Option, + /// Set for a connection that only delivers the CancelRequest for this query. + pub cancel: Option>, } impl PostgresSQLConnection { @@ -1300,7 +1307,8 @@ impl PostgresSQLConnection { pending_activity_count: AtomicU32::new(0), js_value: JsCell::new(crate::jsc::JsRef::empty()), backend_parameters: JsCell::new(StringMap::init(true)), - backend_key_data: JsCell::new(cancel.unwrap_or_default()), + backend_key_data: JsCell::new(protocol::BackendKeyData::default()), + cancel_target: JsCell::new(cancel), database, user: username, password, @@ -1647,11 +1655,28 @@ impl PostgresSQLConnection { .is_some_and(|f| core::ptr::eq(f.as_ptr(), request)) } - /// Asks the server, on a second connection like this one, to cancel what this backend runs. - pub(crate) fn send_cancel_request(&self) { - let key = self.backend_key_data.get(); + /// Whether `request` is the FIFO head and the backend has not finished it. + fn is_running(&self, request: &PostgresSQLQuery) -> bool { + self.is_current_request(request) + && matches!( + request.status.get(), + QueryStatus::Binding | QueryStatus::Running | QueryStatus::PartialResponse + ) + } + + /// The CancelRequest for `request`, while the backend of its session still runs it. + fn cancel_request_for(request: &PostgresSQLQuery) -> Option<[u8; 16]> { + let query = request.this_value.get().try_get()?; + let session = js::from_js_ref(postgres_sql_query::js::connection_get_cached(query)?)?; + session + .is_running(request) + .then(|| session.backend_key_data.get().cancel_request()) + } + + /// Asks the server, on a second connection like this one, to cancel `request`, which this backend runs. + pub(crate) fn send_cancel_request(&self, request: &PostgresSQLQuery) { // No BackendKeyData was ever received, so the server cannot be asked. - if key.process_id == 0 { + if self.backend_key_data.get().process_id == 0 { return; } let socket = self.socket.get(); @@ -1720,10 +1745,7 @@ impl PostgresSQLConnection { use_unnamed_prepared_statements: false, on_connect: JSValue::ZERO, on_close: JSValue::ZERO, - cancel: Some(protocol::BackendKeyData { - process_id: key.process_id, - secret_key: key.secret_key, - }), + cancel: Some(request.ref_guard()), }, ); // Best effort: a cancel that cannot be dialed leaves the query running. diff --git a/src/sql_jsc/postgres/PostgresSQLQuery.rs b/src/sql_jsc/postgres/PostgresSQLQuery.rs index 91516661ddc5..d7513a73cc9f 100644 --- a/src/sql_jsc/postgres/PostgresSQLQuery.rs +++ b/src/sql_jsc/postgres/PostgresSQLQuery.rs @@ -894,7 +894,7 @@ impl PostgresSQLQuery { return Ok(JSValue::UNDEFINED); } - connection.send_cancel_request(); + connection.send_cancel_request(this); Ok(JSValue::UNDEFINED) } } diff --git a/test/js/sql/postgres-query-cancel.test.ts b/test/js/sql/postgres-query-cancel.test.ts index 78d4343110c4..24050868a5e2 100644 --- a/test/js/sql/postgres-query-cancel.test.ts +++ b/test/js/sql/postgres-query-cancel.test.ts @@ -10,7 +10,17 @@ // cancelled before it was dispatched never settled at all. import { SQL } from "bun"; import { expect, test } from "bun:test"; -import { bunEnv, bunExe, expiredTls, isIPv6, isMusl, isWindows, tempDir, tls as tlsCert } from "harness"; +import { + bunEnv, + bunExe, + describeWithContainer, + expiredTls, + isIPv6, + isMusl, + isWindows, + tempDir, + tls as tlsCert, +} from "harness"; import { readFileSync } from "node:fs"; import net from "node:net"; import { join } from "node:path"; @@ -61,7 +71,8 @@ const SSL_REQUEST = Buffer.from([0, 0, 0, 8, 0x04, 0xd2, 0x16, 0x2f]); * * `cancelConnection` makes the second connection meet a server no real backend is: * one that answers a CancelRequest like the start of a session and does not hang - * up, one that declines TLS, or one whose certificate the session's CA did not sign. + * up, one that declines TLS, one whose certificate the session's CA did not sign, + * or one that answers the SSLRequest only when the test calls `answerCancelConnection()`. */ async function backend( options: { @@ -69,13 +80,14 @@ async function backend( certificate?: { cert: string; key: string }; host?: string; socketPath?: string; - cancelConnection?: "answers" | "declines-tls" | "other-certificate"; + cancelConnection?: "answers" | "declines-tls" | "other-certificate" | "waits"; } = {}, ) { const host = options.host ?? "127.0.0.1"; const plaintext: Buffer[] = []; const cancelPacket = Promise.withResolvers(); const cancelConnectionClosed = Promise.withResolvers(); + const cancelConnectionWaiting = Promise.withResolvers<() => void>(); const queryConnectionClosed = Promise.withResolvers(); const sockets = new Set(); const waiters = new Map void>(); @@ -130,11 +142,15 @@ async function backend( rawSocket.pause(); const leftover = buffered.subarray(SSL_REQUEST.length); if (leftover.length) rawSocket.unshift(leftover); - rawSocket.write("S"); - const certificate = cancel === "other-certificate" ? expiredTls : (options.certificate ?? tlsCert); - const secure = new tls.TLSSocket(rawSocket, { isServer: true, ...certificate }); - secure.on("error", () => {}); - serve(connection, secure); + const answer = () => { + rawSocket.write("S"); + const certificate = cancel === "other-certificate" ? expiredTls : (options.certificate ?? tlsCert); + const secure = new tls.TLSSocket(rawSocket, { isServer: true, ...certificate }); + secure.on("error", () => {}); + serve(connection, secure); + }; + if (cancel === "waits") cancelConnectionWaiting.resolve(answer); + else answer(); }; rawSocket.on("data", onPlaintext); }); @@ -187,6 +203,12 @@ async function backend( cancelPacket: cancelPacket.promise, /** Resolves once the second connection is closed. */ cancelConnectionClosed: cancelConnectionClosed.promise, + /** With `waits`: resolves once the second connection has sent its SSLRequest, which is not answered yet. */ + cancelConnectionWaiting: cancelConnectionWaiting.promise.then(() => {}), + /** With `waits`: answers that SSLRequest with `S`, so that the TLS handshake can run. */ + async answerCancelConnection() { + (await cancelConnectionWaiting.promise)(); + }, get cancelPacketSeen() { return cancelPacketSeen; }, @@ -462,6 +484,37 @@ test("the cancel connection closes when the server answers it", async () => { expect((await settled).errno).toBe("57014"); }); +// The dial of the cancel connection is a TCP handshake and, for a TLS session, an +// SSLRequest and a TLS handshake. The query can end in that time, and a +// CancelRequest that is sent then stops the query that the backend runs next. So +// the cancel connection looks at its query again when it is ready to write. +test("the cancel connection sends nothing when its query ended during the dial", async () => { + await using server = await backend({ tls: true, cancelConnection: "waits" }); + server.autoReply = false; + await using sql = new SQL({ url: server.url, tls: { ca: tlsCert.cert }, max: 1, connectionTimeout: 5 }); + + const query = sql`select pg_sleep(10)`.execute(); + await server.untilQueryUnits(1); + query.cancel(); + await server.cancelConnectionWaiting; + + // The query ends by itself while the cancel connection waits for its `S`. + server.reply( + pgParseComplete(), + pgParameterDescription([]), + pgRowDescription([{ name: "v", typeOid: TEXT_OID }]), + pgBindComplete(), + pgDataRow([Buffer.from("done")]), + pgCommandComplete("SELECT 1"), + pgReadyForQuery(), + ); + expect(await query).toEqual([{ v: "done" }]); + + await server.answerCancelConnection(); + await server.cancelConnectionClosed; + expect(server.cancelPacketSeen).toBe(false); +}); + // A dial to an IP literal is a socket before it is open, and uSockets reports // nothing when the timeout of the cancel connection closes it. The connection // has to release the event loop itself, or the process never exits. @@ -692,3 +745,33 @@ test("cancel() on a pipelined query does not cancel the one the backend is runni // Two round trips after the cancel, a cancel connection would have arrived. expect(server.connections).toBe(1); }); + +// The scripted backend compares the packet with `pgCancelRequest`, which this +// change also wrote. Here a real server is the judge of the bytes. +describeWithContainer("postgres", { image: "postgres_plain" }, container => { + test("cancel() stops a query that a real server is running", async () => { + await container.ready; + const url = `postgres://bun_sql_test@${container.host}:${container.port}/bun_sql_test`; + await using sql = new SQL({ url, max: 1, connectionTimeout: 5 }); + await using observer = new SQL({ url, max: 1, connectionTimeout: 5 }); + + const query = sql`select pg_sleep(30) as cancel_running_query`.execute(); + const settled = query.then( + rows => rows, + err => err, + ); + // The backend is inside pg_sleep, so the server runs the query and does not only hold its bytes. + while (true) { + const [{ sleeping }] = await observer` + select count(*)::int as sleeping from pg_stat_activity + where wait_event = 'PgSleep' and query like '%cancel_running_query%' and pid <> pg_backend_pid()`; + if (sleeping) break; + } + query.cancel(); + + const err = await settled; + expect({ code: err.code, errno: err.errno }).toEqual({ code: "ERR_POSTGRES_SERVER_ERROR", errno: "57014" }); + // The connection is in sync: the next query runs on it. + expect(await sql`select 1 as x`).toEqual([{ x: 1 }]); + }); +}); From c55aa7ab13673485802e85871e9d153b9fa73837 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 30 Sep 2026 04:57:11 +0000 Subject: [PATCH 29/34] test(sql): give the pg_sleep poll of the real-server cancel test a deadline The loop now fails after 4 s with the rows that pg_stat_activity has for the query, in place of a test timeout with no message. --- test/js/sql/postgres-query-cancel.test.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/test/js/sql/postgres-query-cancel.test.ts b/test/js/sql/postgres-query-cancel.test.ts index 24050868a5e2..655cca80d1a0 100644 --- a/test/js/sql/postgres-query-cancel.test.ts +++ b/test/js/sql/postgres-query-cancel.test.ts @@ -761,11 +761,13 @@ describeWithContainer("postgres", { image: "postgres_plain" }, container => { err => err, ); // The backend is inside pg_sleep, so the server runs the query and does not only hold its bytes. + const deadline = performance.now() + 4_000; while (true) { - const [{ sleeping }] = await observer` - select count(*)::int as sleeping from pg_stat_activity - where wait_event = 'PgSleep' and query like '%cancel_running_query%' and pid <> pg_backend_pid()`; - if (sleeping) break; + const seen = await observer` + select state, wait_event from pg_stat_activity + where query like '%cancel_running_query%' and pid <> pg_backend_pid()`; + if (seen.some((row: any) => row.wait_event === "PgSleep")) break; + if (performance.now() > deadline) throw new Error(`the query did not reach pg_sleep: ${JSON.stringify(seen)}`); } query.cancel(); From 950a49cb4a47594d81f967c2546429de9c9fb279 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Wed, 30 Sep 2026 07:03:42 +0000 Subject: [PATCH 30/34] sql(postgres): cancel a query whose session closed, and decide at the end of the TLS handshake The cancel connection now holds its session and its query. It sends no CancelRequest only when the session is still connected and its backend runs another query by now. A session that is closed or failed has nothing left that the packet could stop by mistake. Before, reserved.close(), which cancels its queries and closes the connection in the same tick, got no CancelRequest, and the backend ran the query to its end. For a TLS session the cancel connection now decides when the handshake has ended. Before, it decided when the handshake started, so a query that ended during the handshake still got a CancelRequest, which stopped the next query of that backend. --- src/sql_jsc/postgres/PostgresSQLConnection.rs | 51 ++++++--- test/js/sql/postgres-query-cancel.test.ts | 101 +++++++++++++----- 2 files changed, 106 insertions(+), 46 deletions(-) diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index 7442da45c4c6..8a04610ae742 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -141,8 +141,8 @@ pub struct PostgresSQLConnection { pub(crate) backend_parameters: JsCell, pub(crate) backend_key_data: JsCell, - /// The query that a cancel connection stops, until it writes the CancelRequest. - cancel_target: JsCell>>, + /// What a cancel connection stops, until it writes the CancelRequest or fails. + cancel_target: JsCell>, // Self-referential — `database`/`user`/`password`/`path`/`options` are slices // into `options_buf` (built by `ConnectionStrings::new`). Struct is Box-allocated @@ -516,7 +516,10 @@ impl PostgresSQLConnection { })); // ext is now repointed; safe to kick the handshake (any dispatch lands here). sock.start_tls_handshake(); - self.start(); + // A cancel connection decides what to write when the handshake has ended. + if !self.is_cancel_request() { + self.start(); + } } fn setup_max_lifetime_timer_if_necessary(&self) { @@ -748,6 +751,8 @@ impl PostgresSQLConnection { } self.status.set(Status::Failed); + // A cancel connection that fails before it writes lets go of its session and query here. + self.cancel_target.set(None); let _guard = self.ref_guard(); // we defer the refAndClose so the on_close will be called first before we reject the pending requests @@ -848,8 +853,7 @@ impl PostgresSQLConnection { self.status.set(Status::SentStartupMessage); if self.is_cancel_request() { let target = self.cancel_target.with_mut(Option::take); - // The query can end during the dial, and a CancelRequest then stops the next query. - let Some(packet) = target.and_then(|request| Self::cancel_request_for(&request)) else { + let Some(packet) = target.and_then(|target| target.cancel_request()) else { self.fail(b"Connection closed", AnyPostgresError::ConnectionClosed); return; }; @@ -952,6 +956,7 @@ impl PostgresSQLConnection { if !ok { let v = verify_error_to_js(&ssl_error, self.global()); self.fail_with_js_value(v); + return; } } } @@ -959,6 +964,9 @@ impl PostgresSQLConnection { SSLMode::Require | SSLMode::Prefer | SSLMode::Disable => {} } } + if self.is_cancel_request() { + self.start(); + } } else { // if we are here is because server rejected us, and the error_no is the cause of this // no matter if reject_unauthorized is false because we are disconnected by the server @@ -1241,8 +1249,23 @@ pub(crate) struct ConnectParams<'a> { pub use_unnamed_prepared_statements: bool, pub on_connect: JSValue, pub on_close: JSValue, - /// Set for a connection that only delivers the CancelRequest for this query. - pub cancel: Option>, + /// Set for a connection that only delivers the CancelRequest for this target. + pub cancel: Option, +} + +/// The query that a cancel connection stops, and the session whose backend runs it. +pub(crate) struct CancelTarget { + session: RefPtr, + request: RefPtr, +} + +impl CancelTarget { + /// `None` when the session is still connected and its backend runs another query by now. + fn cancel_request(&self) -> Option<[u8; 16]> { + let session = &*self.session; + (session.status.get() != Status::Connected || session.is_running(&self.request)) + .then(|| session.backend_key_data.get().cancel_request()) + } } impl PostgresSQLConnection { @@ -1664,15 +1687,6 @@ impl PostgresSQLConnection { ) } - /// The CancelRequest for `request`, while the backend of its session still runs it. - fn cancel_request_for(request: &PostgresSQLQuery) -> Option<[u8; 16]> { - let query = request.this_value.get().try_get()?; - let session = js::from_js_ref(postgres_sql_query::js::connection_get_cached(query)?)?; - session - .is_running(request) - .then(|| session.backend_key_data.get().cancel_request()) - } - /// Asks the server, on a second connection like this one, to cancel `request`, which this backend runs. pub(crate) fn send_cancel_request(&self, request: &PostgresSQLQuery) { // No BackendKeyData was ever received, so the server cannot be asked. @@ -1745,7 +1759,10 @@ impl PostgresSQLConnection { use_unnamed_prepared_statements: false, on_connect: JSValue::ZERO, on_close: JSValue::ZERO, - cancel: Some(request.ref_guard()), + cancel: Some(CancelTarget { + session: self.ref_guard(), + request: request.ref_guard(), + }), }, ); // Best effort: a cancel that cannot be dialed leaves the query running. diff --git a/test/js/sql/postgres-query-cancel.test.ts b/test/js/sql/postgres-query-cancel.test.ts index 655cca80d1a0..01a8396ac5bd 100644 --- a/test/js/sql/postgres-query-cancel.test.ts +++ b/test/js/sql/postgres-query-cancel.test.ts @@ -72,7 +72,8 @@ const SSL_REQUEST = Buffer.from([0, 0, 0, 8, 0x04, 0xd2, 0x16, 0x2f]); * `cancelConnection` makes the second connection meet a server no real backend is: * one that answers a CancelRequest like the start of a session and does not hang * up, one that declines TLS, one whose certificate the session's CA did not sign, - * or one that answers the SSLRequest only when the test calls `answerCancelConnection()`. + * or one that stops in the dial until the test calls `answerCancelConnection()`: + * before it answers the SSLRequest, or after its `S` and before the TLS handshake. */ async function backend( options: { @@ -80,7 +81,7 @@ async function backend( certificate?: { cert: string; key: string }; host?: string; socketPath?: string; - cancelConnection?: "answers" | "declines-tls" | "other-certificate" | "waits"; + cancelConnection?: "answers" | "declines-tls" | "other-certificate" | "holds-ssl-answer" | "holds-handshake"; } = {}, ) { const host = options.host ?? "127.0.0.1"; @@ -142,15 +143,30 @@ async function backend( rawSocket.pause(); const leftover = buffered.subarray(SSL_REQUEST.length); if (leftover.length) rawSocket.unshift(leftover); - const answer = () => { - rawSocket.write("S"); + const handshake = () => { const certificate = cancel === "other-certificate" ? expiredTls : (options.certificate ?? tlsCert); const secure = new tls.TLSSocket(rawSocket, { isServer: true, ...certificate }); secure.on("error", () => {}); serve(connection, secure); }; - if (cancel === "waits") cancelConnectionWaiting.resolve(answer); - else answer(); + if (cancel === "holds-ssl-answer") { + cancelConnectionWaiting.resolve(() => { + rawSocket.write("S"); + handshake(); + }); + } else if (cancel === "holds-handshake") { + rawSocket.write("S"); + // The ClientHello shows that the client is in the handshake now. + rawSocket.once("data", clientHello => { + rawSocket.pause(); + rawSocket.unshift(clientHello); + cancelConnectionWaiting.resolve(handshake); + }); + rawSocket.resume(); + } else { + rawSocket.write("S"); + handshake(); + } }; rawSocket.on("data", onPlaintext); }); @@ -203,9 +219,9 @@ async function backend( cancelPacket: cancelPacket.promise, /** Resolves once the second connection is closed. */ cancelConnectionClosed: cancelConnectionClosed.promise, - /** With `waits`: resolves once the second connection has sent its SSLRequest, which is not answered yet. */ + /** Resolves once the second connection has stopped in its dial, for the two modes that hold it. */ cancelConnectionWaiting: cancelConnectionWaiting.promise.then(() => {}), - /** With `waits`: answers that SSLRequest with `S`, so that the TLS handshake can run. */ + /** Lets the second connection finish its dial. */ async answerCancelConnection() { (await cancelConnectionWaiting.promise)(); }, @@ -487,32 +503,59 @@ test("the cancel connection closes when the server answers it", async () => { // The dial of the cancel connection is a TCP handshake and, for a TLS session, an // SSLRequest and a TLS handshake. The query can end in that time, and a // CancelRequest that is sent then stops the query that the backend runs next. So -// the cancel connection looks at its query again when it is ready to write. -test("the cancel connection sends nothing when its query ended during the dial", async () => { - await using server = await backend({ tls: true, cancelConnection: "waits" }); +// the cancel connection looks at its query again when the dial has ended, which +// for TLS is the end of the handshake. +test.each(["holds-ssl-answer", "holds-handshake"] as const)( + "the cancel connection sends nothing when its query ended during the dial (%s)", + async cancelConnection => { + await using server = await backend({ tls: true, cancelConnection }); + server.autoReply = false; + await using sql = new SQL({ url: server.url, tls: { ca: tlsCert.cert }, max: 1, connectionTimeout: 5 }); + + const query = sql`select pg_sleep(10)`.execute(); + await server.untilQueryUnits(1); + query.cancel(); + await server.cancelConnectionWaiting; + + // The query ends by itself while the cancel connection is held in its dial. + server.reply( + pgParseComplete(), + pgParameterDescription([]), + pgRowDescription([{ name: "v", typeOid: TEXT_OID }]), + pgBindComplete(), + pgDataRow([Buffer.from("done")]), + pgCommandComplete("SELECT 1"), + pgReadyForQuery(), + ); + expect(await query).toEqual([{ v: "done" }]); + + await server.answerCancelConnection(); + await server.cancelConnectionClosed; + expect(server.cancelPacketSeen).toBe(false); + }, +); + +// reserved.close() cancels its running queries and closes the connection in the +// same tick, so the session is gone when the cancel connection is ready to write. +// The backend still runs the query, and nothing else of this client can reach that +// backend, so the CancelRequest has to go out. +test("cancel() still reaches the server when the session closes during the dial", async () => { + await using server = await backend(); server.autoReply = false; - await using sql = new SQL({ url: server.url, tls: { ca: tlsCert.cert }, max: 1, connectionTimeout: 5 }); + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); - const query = sql`select pg_sleep(10)`.execute(); + const reserved = await sql.reserve(); + const query = reserved`select pg_sleep(10)`.execute(); + const settled = query.then( + rows => rows, + err => err, + ); await server.untilQueryUnits(1); - query.cancel(); - await server.cancelConnectionWaiting; - // The query ends by itself while the cancel connection waits for its `S`. - server.reply( - pgParseComplete(), - pgParameterDescription([]), - pgRowDescription([{ name: "v", typeOid: TEXT_OID }]), - pgBindComplete(), - pgDataRow([Buffer.from("done")]), - pgCommandComplete("SELECT 1"), - pgReadyForQuery(), - ); - expect(await query).toEqual([{ v: "done" }]); + await reserved.close(); - await server.answerCancelConnection(); - await server.cancelConnectionClosed; - expect(server.cancelPacketSeen).toBe(false); + expect(await server.cancelPacket).toEqual(pgCancelRequest(PROCESS_ID, SECRET_KEY)); + expect((await settled).code).toBe("ERR_POSTGRES_CONNECTION_CLOSED"); }); // A dial to an IP literal is a socket before it is open, and uSockets reports From a46f129afcaaea0ef8f4df0d3dced63259466b73 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 2 Oct 2026 10:23:27 +0000 Subject: [PATCH 31/34] sql(postgres): keep a query off the wire when the code of its parameter cancels it The connection encodes the Bind of a query when it converts the parameters, and an object parameter is converted by its own code. That code can call cancel() on the query. - advance() takes a request out of `pending_requests` before it encodes the Bind, and cancel() took it out again: "pending_requests underflow". `RequestCounter::Pending` now records that a request is in that counter, so `finish_request` is idempotent for all three counters. - `encode_request` stops when the request was rejected while its parameters were encoded, and the batch leaves the write buffer. - A cancel() that arrives while `do_run` is on the stack marks the query, and `do_run` does not send it. - `PostgresSQLConnection::cancel` decides what cancel() does. The query only finds its connection. Also: - The cancel key is an `Option`. A process id of 0 is a key, and a server that sent no BackendKeyData has none. - `query.ts` is main's again. The query that is cancelled before it runs is #41492. - The docs say what cancel() does on PostgreSQL and make no claim for the other adapters. --- docs/runtime/sql.mdx | 4 +- packages/bun-types/sql.d.ts | 20 +- src/js/internal/sql/query.ts | 10 +- src/sql/postgres/protocol/BackendKeyData.rs | 1 - src/sql_jsc/postgres/PostgresRequest.rs | 73 ++-- src/sql_jsc/postgres/PostgresSQLConnection.rs | 128 +++--- src/sql_jsc/postgres/PostgresSQLQuery.rs | 73 ++-- test/js/sql/postgres-query-cancel.test.ts | 397 +++++++++++++++--- 8 files changed, 498 insertions(+), 208 deletions(-) diff --git a/docs/runtime/sql.mdx b/docs/runtime/sql.mdx index be713c42a31a..c9ce3d978e29 100644 --- a/docs/runtime/sql.mdx +++ b/docs/runtime/sql.mdx @@ -481,8 +481,8 @@ await query; On PostgreSQL, what `cancel()` does depends on how far the query got: -- A query that Bun has not sent yet never runs. It rejects with `ERR_POSTGRES_QUERY_CANCELLED`. -- A query that the server is running can only be stopped from a separate connection. Bun opens one to the same server, encrypted when the session is, and sends a `CancelRequest` on it. This is a request. If the server stops the query, the query rejects with SQLSTATE `57014`. If the query finishes first, it resolves as usual, and the request can stop the next query on that connection instead. The server also ignores a request that arrives before the query does, which can happen when you cancel a query with megabytes of parameters at once. +- A query that was started and that Bun has not sent yet never runs. It rejects with `ERR_POSTGRES_QUERY_CANCELLED`. +- A query that the server is running can only be stopped from a separate connection. Bun opens one to the same server, encrypted when the session is, and sends a `CancelRequest` on it. This is a request. If the server stops the query, the query rejects with SQLSTATE `57014`. If the query finishes first, it resolves as usual, and the request can stop the next query on that connection instead. The server also ignores a request that arrives before the query does, which can happen when you cancel a query with megabytes of parameters at once. A server that sent no cancel key when the connection opened, as some connection poolers do, cannot be asked: the query runs on. - A query that Bun already sent behind another query on the same connection also rejects with `ERR_POSTGRES_QUERY_CANCELLED`, but the server still runs it. The `hint` of the error says so. An `INSERT` or `UPDATE` in such a query still takes effect, so do not retry it blindly. --- diff --git a/packages/bun-types/sql.d.ts b/packages/bun-types/sql.d.ts index e69f86da763b..4f5777597e83 100644 --- a/packages/bun-types/sql.d.ts +++ b/packages/bun-types/sql.d.ts @@ -472,17 +472,15 @@ declare module "bun" { /** * Requests cancellation of the query. * - * A query that has not been sent to the database never runs. It rejects - * with the adapter's query-cancelled error (for example - * `ERR_POSTGRES_QUERY_CANCELLED`). - * - * For PostgreSQL, a query the server is running is cancelled with a - * `CancelRequest` on a second connection. If the server stops the query, it - * rejects with SQLSTATE 57014. If the query finishes first, it resolves as - * usual, and the request can stop the next query on that connection - * instead. The server ignores a request that arrives before the query - * does. A query that was already sent behind another query rejects with - * `ERR_POSTGRES_QUERY_CANCELLED` and a `hint`, but the server still runs it. + * For PostgreSQL, a query that was started and is not sent yet never runs. + * It rejects with `ERR_POSTGRES_QUERY_CANCELLED`. A query the server is + * running is cancelled with a `CancelRequest` on a second connection. If + * the server stops the query, it rejects with SQLSTATE 57014. If the query + * finishes first, it resolves as usual, and the request can stop the next + * query on that connection instead. The server ignores a request that + * arrives before the query does. A query that was already sent behind + * another query rejects with `ERR_POSTGRES_QUERY_CANCELLED` and a `hint`, + * but the server still runs it. */ cancel(): Query; diff --git a/src/js/internal/sql/query.ts b/src/js/internal/sql/query.ts index 331432cd8ed2..b037f80a2308 100644 --- a/src/js/internal/sql/query.ts +++ b/src/js/internal/sql/query.ts @@ -101,7 +101,10 @@ class Query> extends PublicPromise { #run() { const { [_handler]: handler, [_queryStatus]: status } = this; - if (status & (SQLQueryStatus.executed | SQLQueryStatus.error | SQLQueryStatus.invalidHandle)) { + if ( + status & + (SQLQueryStatus.executed | SQLQueryStatus.error | SQLQueryStatus.cancelled | SQLQueryStatus.invalidHandle) + ) { return; } @@ -128,7 +131,10 @@ class Query> extends PublicPromise { async #runAsync() { const { [_handler]: handler, [_queryStatus]: status } = this; - if (status & (SQLQueryStatus.executed | SQLQueryStatus.error | SQLQueryStatus.invalidHandle)) { + if ( + status & + (SQLQueryStatus.executed | SQLQueryStatus.error | SQLQueryStatus.cancelled | SQLQueryStatus.invalidHandle) + ) { return; } diff --git a/src/sql/postgres/protocol/BackendKeyData.rs b/src/sql/postgres/protocol/BackendKeyData.rs index 892d16fbf982..33e27e8ec2dd 100644 --- a/src/sql/postgres/protocol/BackendKeyData.rs +++ b/src/sql/postgres/protocol/BackendKeyData.rs @@ -4,7 +4,6 @@ use crate::postgres::AnyPostgresError; /// CancelRequest's stand-in for the protocol version: `(1234 << 16) | 5678`. const CANCEL_REQUEST_CODE: u32 = 80877102; -#[derive(Default)] pub struct BackendKeyData { pub process_id: u32, pub secret_key: u32, diff --git a/src/sql_jsc/postgres/PostgresRequest.rs b/src/sql_jsc/postgres/PostgresRequest.rs index a3af1fcb24ca..1053f0a25b11 100644 --- a/src/sql_jsc/postgres/PostgresRequest.rs +++ b/src/sql_jsc/postgres/PostgresRequest.rs @@ -454,40 +454,53 @@ pub(crate) enum EncodeRequest<'a> { } impl PostgresSQLConnection { - /// The only caller of the batch writers above. + /// The only caller of the batch writers above. The code of a parameter runs while its Bind is + /// encoded. If that code got `request` rejected, nothing of the batch stays in the buffer. pub(crate) fn encode_request( &self, global: &JSGlobalObject, - request: EncodeRequest<'_>, + request: &PostgresSQLQuery, + batch: EncodeRequest<'_>, ) -> Result<(), AnyPostgresError> { - let writer = self.writer(); - match request { - EncodeRequest::BindAndExecute { - statement, - binding_value, - columns_value, - } => bind_and_execute(global, statement, binding_value, columns_value, writer), - EncodeRequest::ParseBindAndExecute { - query, - statement, - binding_value, - columns_value, - include_describe, - } => parse_and_bind_and_execute( - global, - query, - statement, - binding_value, - columns_value, - include_describe, - writer, - ), - EncodeRequest::PrepareAndQuery { - query, - signature, - binding_value, - } => prepare_and_query_with_signature(global, query, binding_value, writer, signature), - } + self.writer().atomically(|writer| { + match batch { + EncodeRequest::BindAndExecute { + statement, + binding_value, + columns_value, + } => bind_and_execute(global, statement, binding_value, columns_value, writer), + EncodeRequest::ParseBindAndExecute { + query, + statement, + binding_value, + columns_value, + include_describe, + } => parse_and_bind_and_execute( + global, + query, + statement, + binding_value, + columns_value, + include_describe, + writer, + ), + EncodeRequest::PrepareAndQuery { + query, + signature, + binding_value, + } => prepare_and_query_with_signature( + global, + query, + binding_value, + writer, + signature, + ), + }?; + if request.is_rejected() { + return Err(AnyPostgresError::QueryCancelled); + } + Ok(()) + }) } } diff --git a/src/sql_jsc/postgres/PostgresSQLConnection.rs b/src/sql_jsc/postgres/PostgresSQLConnection.rs index b267be3728f7..1525a99d340e 100644 --- a/src/sql_jsc/postgres/PostgresSQLConnection.rs +++ b/src/sql_jsc/postgres/PostgresSQLConnection.rs @@ -140,7 +140,7 @@ pub struct PostgresSQLConnection { pub(crate) js_value: JsCell, pub(crate) backend_parameters: JsCell, - pub(crate) backend_key_data: JsCell, + pub(crate) backend_key_data: JsCell>, /// What a cancel connection stops, until it writes the CancelRequest or fails. cancel_target: JsCell>, @@ -1263,8 +1263,11 @@ impl CancelTarget { /// `None` when the session is still connected and its backend runs another query by now. fn cancel_request(&self) -> Option<[u8; 16]> { let session = &*self.session; - (session.status.get() != Status::Connected || session.is_running(&self.request)) - .then(|| session.backend_key_data.get().cancel_request()) + if session.status.get() == Status::Connected && !session.is_running(&self.request) { + return None; + } + let key = session.backend_key_data.get().as_ref()?; + Some(key.cancel_request()) } } @@ -1330,7 +1333,7 @@ impl PostgresSQLConnection { pending_activity_count: AtomicU32::new(0), js_value: JsCell::new(crate::jsc::JsRef::empty()), backend_parameters: JsCell::new(StringMap::init(true)), - backend_key_data: JsCell::new(protocol::BackendKeyData::default()), + backend_key_data: JsCell::new(None), cancel_target: JsCell::new(cancel), database, user: username, @@ -1564,7 +1567,7 @@ impl PostgresSQLConnection { match request.status.get() { // pending we will fail the request and the stmt will be marked as error ConnectionClosed too QueryStatus::Pending => { - self.note_request_written(); + self.finish_request(&request); let Some(stmt) = request.statement_mut() else { // The deref/discard at the bottom of the loop is intentionally skipped here. continue; @@ -1678,10 +1681,44 @@ impl PostgresSQLConnection { ) } + /// `Query.cancel()` on a request that was dispatched to this connection. + pub(crate) fn cancel(&self, request: &PostgresSQLQuery) { + let global = self.global(); + match request.status.get() { + QueryStatus::Success | QueryStatus::Fail => {} + // Its Bind, Execute or Query is not written, and a request that failed never writes one. + QueryStatus::Pending => { + let err = postgres_error_to_js( + global, + Some(b"Query cancelled"), + AnyPostgresError::QueryCancelled, + ); + self.finish_request(request); + request.on_js_error(err, global); + } + // A CancelRequest names the backend process, so it stops what the backend runs: the FIFO head. + QueryStatus::Binding | QueryStatus::Running | QueryStatus::PartialResponse + if self.is_current_request(request) => + { + self.send_cancel_request(request); + } + // Written behind the head: the backend runs it whatever this client does. + QueryStatus::Binding | QueryStatus::Running | QueryStatus::PartialResponse => { + let err = postgres_error_to_js_with_hint( + global, + Some(b"Query cancelled"), + Some(b"The server already received this query and still runs it. Bun discards the result."), + AnyPostgresError::QueryCancelled, + ); + request.reject_in_flight(err, global); + } + } + } + /// Asks the server, on a second connection like this one, to cancel `request`, which this backend runs. - pub(crate) fn send_cancel_request(&self, request: &PostgresSQLQuery) { - // No BackendKeyData was ever received, so the server cannot be asked. - if self.backend_key_data.get().process_id == 0 { + fn send_cancel_request(&self, request: &PostgresSQLQuery) { + // A server that sent no BackendKeyData cannot be asked. + if self.backend_key_data.get().is_none() { return; } let socket = self.socket.get(); @@ -1784,18 +1821,14 @@ impl PostgresSQLConnection { || self.current().is_some() } + /// Counts `request` as queued with its Bind, Execute or Query not written. #[inline] - pub(crate) fn note_request_pending(&self) { + pub(crate) fn note_request_pending(&self, request: &PostgresSQLQuery) { + debug_assert!(request.flags.get().counter == RequestCounter::None); + request.update_flags(|f| f.counter = RequestCounter::Pending); self.pending_requests.set(self.pending_requests.get() + 1); } - #[inline] - pub(crate) fn note_request_written(&self) { - let n = self.pending_requests.get(); - debug_assert!(n > 0, "pending_requests underflow"); - self.pending_requests.set(n.wrapping_sub(1)); - } - pub(crate) fn can_pipeline(&self) -> bool { if bun_core::env_var::feature_flag::BUN_FEATURE_FLAG_DISABLE_SQL_AUTO_PIPELINING .get() @@ -2002,34 +2035,19 @@ impl PostgresSQLConnection { } } - /// Take `item` out of the connection's request accounting. Call it once, - /// while `item` still has the status it was counted under. + /// Takes `item` out of the connection counter it is in. A second call does nothing. pub(crate) fn finish_request(&self, item: &PostgresSQLQuery) { - match item.status.get() { - QueryStatus::Running | QueryStatus::Binding | QueryStatus::PartialResponse => { - let counter = item.flags.get().counter; - item.update_flags(|f| f.counter = RequestCounter::None); - match counter { - RequestCounter::None => {} - RequestCounter::Nonpipelinable => { - let n = self.nonpipelinable_requests.get(); - debug_assert!(n > 0, "nonpipelinable_requests underflow"); - self.nonpipelinable_requests.set(n.saturating_sub(1)); - } - RequestCounter::Pipelined => { - let n = self.pipelined_requests.get(); - debug_assert!(n > 0, "pipelined_requests underflow"); - self.pipelined_requests.set(n.saturating_sub(1)); - } - } - } - QueryStatus::Pending => { - // ErrorResponse on a Parse-in-flight request: it never reached - // Binding, so account for it leaving the pending set here. - self.note_request_written(); - } - QueryStatus::Success | QueryStatus::Fail => {} - } + let counter = item.flags.get().counter; + item.update_flags(|f| f.counter = RequestCounter::None); + let counted = match counter { + RequestCounter::None => return, + RequestCounter::Pending => &self.pending_requests, + RequestCounter::Nonpipelinable => &self.nonpipelinable_requests, + RequestCounter::Pipelined => &self.pipelined_requests, + }; + let n = counted.get(); + debug_assert!(n > 0, "request counter underflow"); + counted.set(n.saturating_sub(1)); } /// What a request rejects with for a row the client cannot decode. `Err`: the VM is stopping. @@ -2076,6 +2094,10 @@ impl PostgresSQLConnection { req.on_js_error(err_, self.global()); return; } + // `encode_request` stopped for a request that was already rejected. + if req.status.get() == QueryStatus::Fail { + return; + } if let Some(statement) = new_statement { statement.status = StatementStatus::Failed; statement.error_response = Some(StatementError::PostgresError(err)); @@ -2122,7 +2144,7 @@ impl PostgresSQLConnection { // few paths below that keep it Pending (can't execute yet / // Parse written but not Bind / statement still Parsing) undo // this via note_request_pending() before returning/continuing. - self.note_request_written(); + self.finish_request(&req); if req.flags.get().simple { if self.pipelined_requests.get() > 0 || !self @@ -2138,7 +2160,7 @@ impl PostgresSQLConnection { .contains(ConnectionFlags::IS_READY_FOR_QUERY) ); // need to wait for the previous request to finish before starting simple queries - self.note_request_pending(); + self.note_request_pending(&req); defer_cleanup!(self); return; } @@ -2229,6 +2251,7 @@ impl PostgresSQLConnection { let global = self.global_object; if let Err(err) = self.encode_request( &global, + &req, EncodeRequest::ParseBindAndExecute { query: query_str.slice(), statement, @@ -2256,6 +2279,7 @@ impl PostgresSQLConnection { let global = self.global_object; if let Err(err) = self.encode_request( &global, + &req, EncodeRequest::BindAndExecute { statement, binding_value, @@ -2303,7 +2327,7 @@ impl PostgresSQLConnection { "need to wait to finish the pipeline before starting a new query preparation" ); // need to wait to finish the pipeline before starting a new query preparation - self.note_request_pending(); + self.note_request_pending(&req); defer_cleanup!(self); return; } @@ -2335,6 +2359,7 @@ impl PostgresSQLConnection { let global = self.global_object; if let Err(err) = self.encode_request( &global, + &req, EncodeRequest::PrepareAndQuery { query: query_str.slice(), signature: &mut statement.signature, @@ -2399,6 +2424,7 @@ impl PostgresSQLConnection { let global = self.global_object; if let Err(err) = self.encode_request( &global, + &req, EncodeRequest::ParseBindAndExecute { query: query_str.slice(), statement, @@ -2469,20 +2495,20 @@ impl PostgresSQLConnection { statement.status = StatementStatus::Parsing; // Parse+Describe+Sync written; Bind+Execute deferred to the // next advance(), so the request is still pending on the wire. - self.note_request_pending(); + self.note_request_pending(&req); self.flush_data_and_reset_timeout(); defer_cleanup!(self); return; } StatementStatus::Parsing => { // we are still parsing, lets wait for it to be prepared or failed - self.note_request_pending(); + self.note_request_pending(&req); offset += 1; continue; } } } else { - self.note_request_pending(); + self.note_request_pending(&req); offset += 1; continue; } @@ -3171,9 +3197,9 @@ impl PostgresSQLConnection { } MessageType::BackendKeyData => { self.backend_key_data - .set(protocol::BackendKeyData::decode_internal( + .set(Some(protocol::BackendKeyData::decode_internal( reader.reborrow(), - )?); + )?)); } MessageType::ErrorResponse => { let err = protocol::ErrorResponse::decode_internal(reader.reborrow())?; diff --git a/src/sql_jsc/postgres/PostgresSQLQuery.rs b/src/sql_jsc/postgres/PostgresSQLQuery.rs index d7513a73cc9f..c0202fc98b9c 100644 --- a/src/sql_jsc/postgres/PostgresSQLQuery.rs +++ b/src/sql_jsc/postgres/PostgresSQLQuery.rs @@ -14,7 +14,7 @@ use super::PostgresSQLConnection; use super::PostgresSQLStatement; use super::Signature; use super::command_tag_jsc::CommandTagJsc; -use super::error_jsc::{postgres_error_to_js, postgres_error_to_js_with_hint}; +use super::error_jsc::postgres_error_to_js; use super::postgres_request as PostgresRequest; use super::postgres_request::EncodeRequest; use super::postgres_sql_connection; @@ -80,9 +80,9 @@ pub struct Flags { pub(crate) simple: bool, /// Rejected while in flight: its response is skipped until `ReadyForQuery`. pub(crate) discard_response: bool, - /// Which connection counter this request's dispatch incremented; reset to - /// `None` when `finish_request` consumes that contribution, so the - /// decrement is idempotent across its call sites. + /// Which connection counter this request is in; reset to `None` when + /// `finish_request` takes it out, so the decrement is idempotent across + /// its call sites. pub(crate) counter: RequestCounter, pub(crate) result_mode: PostgresSQLQueryResultMode, } @@ -90,6 +90,8 @@ pub struct Flags { #[derive(Clone, Copy, PartialEq, Eq)] pub enum RequestCounter { None, + /// `PostgresSQLConnection::pending_requests` + Pending, /// `PostgresSQLConnection::nonpipelinable_requests` Nonpipelinable, /// `PostgresSQLConnection::pipelined_requests` @@ -501,6 +503,12 @@ impl PostgresSQLQuery { // is already pending. let throw_write_error = |msg: &[u8], err: AnyPostgresError| -> JsError { if !global_object.has_exception() { + // `cancel()` from the code of a parameter stopped the write. The write did not fail. + let msg = if matches!(err, AnyPostgresError::QueryCancelled) { + b"Query cancelled" + } else { + msg + }; return global_object.throw_value(postgres_error_to_js( global_object, Some(msg), @@ -558,7 +566,7 @@ impl PostgresSQLQuery { } connection.requests.with_mut(|q| q.push_back(queued)); if this.status.get() == Status::Pending { - connection.note_request_pending(); + connection.note_request_pending(this); } // Request is enqueued: keep the event loop alive until the server @@ -605,6 +613,14 @@ impl PostgresSQLQuery { } }; + // The code of a binding ran, and it can have called `cancel()`. + if this.is_rejected() { + return Err(throw_write_error( + b"Query cancelled", + AnyPostgresError::QueryCancelled, + )); + } + let has_params = signature.fields.len() > 0; let mut did_write = false; 'enqueue: { @@ -653,6 +669,7 @@ impl PostgresSQLQuery { // bindAndExecute will bind + execute, it will change to running after binding is complete if let Err(err) = connection.encode_request( global_object, + this, EncodeRequest::BindAndExecute { statement: stmt, binding_value, @@ -712,6 +729,7 @@ impl PostgresSQLQuery { // prepareAndQueryWithSignature will write + bind + execute, it will change to running after binding is complete if let Err(err) = connection.encode_request( global_object, + this, EncodeRequest::PrepareAndQuery { query: query_str.slice(), signature: &mut signature, @@ -823,7 +841,7 @@ impl PostgresSQLQuery { connection.requests.with_mut(|q| q.push_back(queued)); if this.status.get() == Status::Pending { - connection.note_request_pending(); + connection.note_request_pending(this); } // Request is enqueued: keep the event loop alive until the server // responds. See the matching call in the simple-query branch above @@ -853,48 +871,21 @@ impl PostgresSQLQuery { pub fn do_cancel( this: &Self, - global_object: &JSGlobalObject, + _global_object: &JSGlobalObject, callframe: &CallFrame, ) -> JsResult { - let this_value = callframe.this(); - let Some(connection_value) = js::connection_get_cached(this_value) else { + // Set from the end of `do_run` until the query settles. + let Some(connection_value) = js::connection_get_cached(callframe.this()) else { + // Not dispatched, or the code of a parameter called this from inside `do_run`. + if this.status.get() == Status::Pending { + this.status.set(Status::Fail); + } return Ok(JSValue::UNDEFINED); }; let Some(connection) = postgres_sql_connection::js::from_js_ref(connection_value) else { return Ok(JSValue::UNDEFINED); }; - - let status = this.status.get(); - if matches!(status, Status::Success | Status::Fail) { - return Ok(JSValue::UNDEFINED); - } - - // A CancelRequest names the backend process, not a statement, so it only - // ever stops the FIFO head. Anything else is settled locally. - if status == Status::Pending { - // No Bind, Execute or Query of it is written, and a Fail entry never writes one. - let err = postgres_error_to_js( - global_object, - Some(b"Query cancelled"), - AnyPostgresError::QueryCancelled, - ); - connection.finish_request(this); - this.on_js_error(err, global_object); - return Ok(JSValue::UNDEFINED); - } - if !connection.is_current_request(this) { - // Already on the wire: the backend runs it regardless, so the error says so. - let err = postgres_error_to_js_with_hint( - global_object, - Some(b"Query cancelled"), - Some(b"The server already received this query and still runs it. Bun discards the result."), - AnyPostgresError::QueryCancelled, - ); - this.reject_in_flight(err, global_object); - return Ok(JSValue::UNDEFINED); - } - - connection.send_cancel_request(this); + connection.cancel(this); Ok(JSValue::UNDEFINED) } } diff --git a/test/js/sql/postgres-query-cancel.test.ts b/test/js/sql/postgres-query-cancel.test.ts index f16e94fbf789..b326fbb7aa04 100644 --- a/test/js/sql/postgres-query-cancel.test.ts +++ b/test/js/sql/postgres-query-cancel.test.ts @@ -6,9 +6,9 @@ // describeWithContainer. All wire bytes come from test/js/sql/wire-frames.ts. // // Query.cancel() used to be a no-op for Postgres: nothing was ever written, so a -// cancelled query ran to completion and resolved with its rows, and a query -// cancelled before it was dispatched never settled at all. +// cancelled query ran to completion and resolved with its rows. import { SQL } from "bun"; +import { heapStats } from "bun:jsc"; import { expect, test } from "bun:test"; import { bunEnv, @@ -71,9 +71,10 @@ const SSL_REQUEST = Buffer.from([0, 0, 0, 8, 0x04, 0xd2, 0x16, 0x2f]); * * `cancelConnection` makes the second connection meet a server no real backend is: * one that answers a CancelRequest like the start of a session and does not hang - * up, one that declines TLS, one whose certificate the session's CA did not sign, - * or one that stops in the dial until the test calls `answerCancelConnection()`: - * before it answers the SSLRequest, or after its `S` and before the TLS handshake. + * up, one that takes the CancelRequest and then stays silent, one that declines + * TLS, one whose certificate the session's CA did not sign, or one that stops in + * the dial until the test calls `answerCancelConnection()`: before it answers the + * SSLRequest, or after its `S` and before the TLS handshake. */ async function backend( options: { @@ -81,7 +82,15 @@ async function backend( certificate?: { cert: string; key: string }; host?: string; socketPath?: string; - cancelConnection?: "answers" | "declines-tls" | "other-certificate" | "holds-ssl-answer" | "holds-handshake"; + cancelConnection?: + | "answers" + | "silent" + | "declines-tls" + | "other-certificate" + | "holds-ssl-answer" + | "holds-handshake"; + /** The BackendKeyData of the session. `null`: the server sends none. */ + key?: { processId: number; secretKey: number } | null; } = {}, ) { const host = options.host ?? "127.0.0.1"; @@ -95,8 +104,10 @@ async function backend( let queryConnection: net.Socket | undefined; let connections = 0; let queryUnits = 0; + let frontendMessages = ""; let autoReply = true; let cancelPacketSeen = false; + const key = options.key === undefined ? { processId: PROCESS_ID, secretKey: SECRET_KEY } : options.key; // Answer a Parse+Describe+Bind+Execute with one text row: ParseComplete and // the two Describe replies, then the Execute replies. @@ -180,6 +191,7 @@ async function backend( if (buffered.length < 16) return; cancelPacketSeen = true; cancelPacket.resolve(buffered); + if (options.cancelConnection === "silent") return; // A real backend acts on the CancelRequest and hangs up. if (options.cancelConnection !== "answers") return void socket.end(); socket.write(Buffer.concat([pgAuthenticationOk(), pgReadyForQuery()])); @@ -195,7 +207,11 @@ async function backend( if (!handshaken) { handshaken = true; socket.write( - Buffer.concat([pgAuthenticationOk(), pgBackendKeyData(PROCESS_ID, SECRET_KEY), pgReadyForQuery()]), + Buffer.concat([ + pgAuthenticationOk(), + ...(key ? [pgBackendKeyData(key.processId, key.secretKey)] : []), + pgReadyForQuery(), + ]), ); return; } @@ -203,6 +219,7 @@ async function backend( // Sync ends every extended-protocol unit; the simple protocol's Query is // its own sync point. const message = String.fromCharCode(type); + frontendMessages += message; if (message === "S" || message === "Q") onQueryUnit(); }); }); @@ -237,6 +254,10 @@ async function backend( get queryUnits() { return queryUnits; }, + /** The type byte of each message the session has sent after its startup message. */ + get frontendMessages() { + return frontendMessages; + }, set autoReply(value: boolean) { autoReply = value; }, @@ -314,31 +335,40 @@ test.each(protocols)("cancel() on a running %s query sends a CancelRequest", asy // The cancel connection has to reach the server the way the session does. A // plaintext one leaks the cancel key of a TLS session, and a server that only // accepts TLS never sees it. -test("cancel() on a TLS session sends the CancelRequest through TLS", async () => { - await using server = await backend({ tls: true }); - server.autoReply = false; - // `ca` makes the session verify-full, so the cancel connection only gets through - // the handshake if it uses the same TLS options. - await using sql = new SQL({ url: server.url, tls: { ca: tlsCert.cert }, max: 1, connectionTimeout: 5 }); +const tlsSessions: [sslmode: string, options: (url: string) => object][] = [ + // `ca` alone makes the session verify-full, so the cancel connection only gets + // through the handshake if it uses the same TLS options. + ["verify-full", url => ({ url, tls: { ca: tlsCert.cert } })], + ["verify-ca", url => ({ url: `${url}?sslmode=verify-ca`, tls: { ca: tlsCert.cert } })], + ["require", url => ({ url: `${url}?sslmode=require` })], + ["prefer", url => ({ url: `${url}?sslmode=prefer` })], +]; +test.each(tlsSessions)( + "cancel() on a TLS session (sslmode=%s) sends the CancelRequest through TLS", + async (_sslmode, options) => { + await using server = await backend({ tls: true }); + server.autoReply = false; + await using sql = new SQL({ ...options(server.url), max: 1, connectionTimeout: 5 }); - const query = sql`select pg_sleep(10)`.execute(); - const settled = query.then( - rows => rows, - err => err, - ); - await server.untilQueryUnits(1); - query.cancel(); + const query = sql`select pg_sleep(10)`.execute(); + const settled = query.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + query.cancel(); - expect(await server.cancelPacket).toEqual(pgCancelRequest(PROCESS_ID, SECRET_KEY)); - // Both connections sent an SSLRequest in the clear, and nothing else. - expect(server.plaintext).toEqual([SSL_REQUEST, SSL_REQUEST]); + expect(await server.cancelPacket).toEqual(pgCancelRequest(PROCESS_ID, SECRET_KEY)); + // Both connections sent an SSLRequest in the clear, and nothing else. + expect(server.plaintext).toEqual([SSL_REQUEST, SSL_REQUEST]); - server.reply( - pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), - pgReadyForQuery(), - ); - expect((await settled).errno).toBe("57014"); -}); + server.reply( + pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), + pgReadyForQuery(), + ); + expect((await settled).errno).toBe("57014"); + }, +); // A session that is encrypted must not lose its cancel key to a cancel connection // that is not. `prefer` counts once the session has negotiated TLS. @@ -500,6 +530,78 @@ test("the cancel connection closes when the server answers it", async () => { expect((await settled).errno).toBe("57014"); }); +// A server that takes the CancelRequest and then neither answers nor hangs up must +// not keep the cancel connection open. The cancel connection has the connection +// timeout of its session, 1 s here, from its dial to its end. +test("the cancel connection ends when the server stays silent after the CancelRequest", async () => { + await using server = await backend({ cancelConnection: "silent" }); + server.autoReply = false; + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 1 }); + + const query = sql`select pg_sleep(10)`.execute(); + const settled = query.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + query.cancel(); + + expect(await server.cancelPacket).toEqual(pgCancelRequest(PROCESS_ID, SECRET_KEY)); + await server.cancelConnectionClosed; + + server.reply( + pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), + pgReadyForQuery(), + ); + expect((await settled).errno).toBe("57014"); +}); + +// Some servers and poolers send no BackendKeyData. Then there is no key to send, +// and the query runs on. +test("cancel() on a running query opens no connection when the server sent no cancel key", async () => { + await using server = await backend({ key: null }); + server.autoReply = false; + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + + const query = sql`select pg_sleep(10)`.simple().execute(); + await server.untilQueryUnits(1); + query.cancel(); + + server.reply( + pgRowDescription([{ name: "v", typeOid: TEXT_OID }]), + pgDataRow([Buffer.from("done")]), + pgCommandComplete("SELECT 1"), + pgReadyForQuery(), + ); + expect(await query).toEqual([{ v: "done" }]); + // A cancel connection would have arrived by the end of one more round trip. + server.autoReply = true; + expect(await sql`select 'next'`).toEqual([{ v: "ok" }]); + expect(server.connections).toBe(1); +}); + +// The process id in a cancel key is opaque to the client, and 0 is a value like any other. +test("cancel() sends a cancel key whose process id is 0", async () => { + await using server = await backend({ key: { processId: 0, secretKey: SECRET_KEY } }); + server.autoReply = false; + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + + const query = sql`select pg_sleep(10)`.execute(); + const settled = query.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + query.cancel(); + + expect(await server.cancelPacket).toEqual(pgCancelRequest(0, SECRET_KEY)); + server.reply( + pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), + pgReadyForQuery(), + ); + expect((await settled).errno).toBe("57014"); +}); + // The dial of the cancel connection is a TCP handshake and, for a TLS session, an // SSLRequest and a TLS handshake. The query can end in that time, and a // CancelRequest that is sent then stops the query that the backend runs next. So @@ -612,27 +714,6 @@ test("cancel() during the Parse of a statement does not fail the queries that sh expect(server.queryUnits).toBe(2); }); -test("cancel() before the query is dispatched rejects it instead of hanging", async () => { - await using server = await backend(); - await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); - - // Tagged templates are lazy: nothing has been sent, and nothing ever will be, - // so the first consumer of the promise has to reject it. - const query = sql`select 1`; - query.cancel(); - - const err = await query.catch((e: any) => e); - expect({ name: err.name, code: err.code, message: err.message }).toEqual({ - name: "PostgresError", - code: "ERR_POSTGRES_QUERY_CANCELLED", - message: "Query cancelled", - }); - // The cancelled query never reaches the server: after a round trip for the next - // query, that query is the only one the server has seen. - expect(await sql`select 'next'`).toEqual([{ v: "ok" }]); - expect(server.queryUnits).toBe(1); -}); - test("cancel() on a queued query does not cancel the one the backend is running", async () => { await using server = await backend(); server.autoReply = false; @@ -716,26 +797,6 @@ test("a connection still pipelines after a queued query on it was cancelled", as expect(await Promise.all([first, second])).toEqual([[{ v: "first" }], [{ v: "second" }]]); }); -// A reserved connection keeps its queries in a scope set, and close({ timeout }) -// waits on that set. Only the query's own handler takes a cancelled query back out -// of it. A rejected query left in the set ends the wait at once, before the -// connection is closed, and the pool never gets the connection back. -test("a query cancelled before it runs leaves the scope of its reserved connection", async () => { - await using server = await backend(); - await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); - - const reserved = await sql.reserve(); - const query = reserved`select 1`; - query.cancel(); - const err = await query.catch((e: any) => e); - expect(err.code).toBe("ERR_POSTGRES_QUERY_CANCELLED"); - - await reserved.close({ timeout: 1 }); - await server.queryConnectionClosed; - // Nothing was ever sent for the cancelled query, so there was nothing to cancel. - expect(server.connections).toBe(1); -}); - // A CancelRequest names the backend process, not a statement. Once a statement is // prepared, Bun pipelines the next query's Bind/Execute straight onto the wire // behind the running one (do_run's Prepared arm writes when `can_pipeline()`), so @@ -789,6 +850,202 @@ test("cancel() on a pipelined query does not cancel the one the backend is runni expect(server.connections).toBe(1); }); +// Under load the query that the backend runs has other queries written behind it. +// The CancelRequest stops the first one, and the server answers the others as usual. +test("cancel() on the running query leaves the queries that are pipelined behind it", async () => { + await using server = await backend(); + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + + expect(await sql`select 'a'`).toEqual([{ v: "ok" }]); + expect(await sql`select 'b'`).toEqual([{ v: "ok" }]); + server.autoReply = false; + + const running = sql`select 'a'`.execute(); + const behind = sql`select 'b'`.execute(); + const runningSettled = running.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(4); + + running.cancel(); + expect(await server.cancelPacket).toEqual(pgCancelRequest(PROCESS_ID, SECRET_KEY)); + server.reply( + pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), + pgReadyForQuery(), + ); + expect((await runningSettled).errno).toBe("57014"); + + server.answerPrepared("kept"); + expect(await behind).toEqual([{ v: "kept" }]); + + // The statement of the cancelled query is still prepared: its next run is a bare Bind and Execute. + const again = sql`select 'a'`.execute(); + await server.untilQueryUnits(5); + server.answerPrepared("again"); + expect(await again).toEqual([{ v: "again" }]); +}); + +// The server still answers a pipelined query that cancel() rejected, and the +// answer can be an error. The connection takes it like the rows of such a query. +test("a cancelled pipelined query that the server answers with an error leaves the connection in sync", async () => { + await using server = await backend(); + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + + expect(await sql`select 'a'`).toEqual([{ v: "ok" }]); + expect(await sql`select 'b'`).toEqual([{ v: "ok" }]); + server.autoReply = false; + + const running = sql`select 'a'`.execute(); + const pipelined = sql`select 'b'`.execute(); + const pipelinedSettled = pipelined.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(4); + + pipelined.cancel(); + expect((await pipelinedSettled).code).toBe("ERR_POSTGRES_QUERY_CANCELLED"); + + server.answerPrepared("kept"); + expect(await running).toEqual([{ v: "kept" }]); + server.reply(pgErrorResponse({ S: "ERROR", C: "22012", M: "division by zero" }), pgReadyForQuery()); + + // The error was for the cancelled query alone: its statement is still prepared. + const again = sql`select 'b'`.execute(); + await server.untilQueryUnits(5); + server.answerPrepared("again"); + expect(await again).toEqual([{ v: "again" }]); + expect(server.connections).toBe(1); +}); + +// The connection turns a parameter into its wire form when it encodes the Bind, +// and an object does that with its own code. That code can call cancel() on the +// query that it belongs to. Nothing of the query is on the wire then, and nothing +// of it may get there. +const cancelling = (query: () => { cancel(): unknown }) => ({ + toString() { + query().cancel(); + return "x"; + }, +}); +const settledCode = (query: Promise) => + query.then( + () => "resolved", + (err: any) => err.code, + ); + +test("cancel() from the code of a parameter rejects the query and sends no Bind for it", async () => { + await using server = await backend(); + server.autoReply = false; + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + const statement = (parameter: object) => sql`select ${parameter}::text as v`; + + // First run: Parse, Describe and Sync go out, and the Bind waits for the + // parameter types. The connection encodes it when they arrive. + const first: any = statement(cancelling(() => first)); + const firstSettled = settledCode(first.execute()); + await server.untilQueryUnits(1); + server.reply( + pgParseComplete(), + pgParameterDescription([TEXT_OID]), + pgRowDescription([{ name: "v", typeOid: TEXT_OID }]), + pgReadyForQuery(), + ); + expect(await firstSettled).toBe("ERR_POSTGRES_QUERY_CANCELLED"); + + // Second run: the statement is prepared, so the Bind is encoded at dispatch. + const second: any = statement(cancelling(() => second)); + expect(await settledCode(second.execute())).toBe("ERR_POSTGRES_QUERY_CANCELLED"); + + // Third run, with a parameter that cancels nothing. Its Bind is the only one + // that the server has seen. + const third = statement({ toString: () => "z" }).execute(); + await server.untilQueryUnits(2); + server.answerPrepared("z"); + expect(await third).toEqual([{ v: "z" }]); + expect({ binds: server.frontendMessages.match(/B/g)?.length, connections: server.connections }).toEqual({ + binds: 1, + connections: 1, + }); +}); + +// Without prepared statements the Parse, the Bind and the Execute of a query are +// one batch, encoded at dispatch. +test("cancel() from the code of a parameter sends nothing when statements are not prepared", async () => { + await using server = await backend(); + server.autoReply = false; + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5, prepare: false }); + + const cancelled: any = sql`select ${cancelling(() => cancelled)}::text as v`; + expect(await settledCode(cancelled.execute())).toBe("ERR_POSTGRES_QUERY_CANCELLED"); + + const next = sql`select ${{ toString: () => "z" }}::text as v`.execute(); + await server.untilQueryUnits(1); + expect(server.frontendMessages.match(/[PB]/g)).toEqual(["P", "B"]); + server.reply( + pgParseComplete(), + pgParameterDescription([TEXT_OID]), + pgRowDescription([{ name: "v", typeOid: TEXT_OID }]), + pgBindComplete(), + pgDataRow([Buffer.from("z")]), + pgCommandComplete("SELECT 1"), + pgReadyForQuery(), + ); + expect(await next).toEqual([{ v: "z" }]); +}); + +// A query caches the connection that it was dispatched to, because cancel() +// needs it. A query that has settled, by any of the ways above, must let go of +// it, or a Query that user code keeps also keeps the connection. +test("a settled query does not keep its connection alive", async () => { + const connections = () => heapStats().objectTypeCounts["PostgresSQLConnection"] || 0; + Bun.gc(true); + const before = connections(); + const kept: unknown[] = []; + const rounds = 10; + + for (let round = 0; round < rounds; round++) { + await using server = await backend(); + const sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + const resolved = sql`select 'a'`.execute(); + await resolved; + server.autoReply = false; + + // The running query, one that is written behind it, and one that is not written. + const running = sql`select 'a'`.execute(); + const pipelined = sql`select 'a'`.execute(); + const queued = sql`select 'q'`.simple().execute(); + const cancelled = [running, pipelined, queued]; + const settled = Promise.all(cancelled.map(settledCode)); + await server.untilQueryUnits(3); + for (const query of cancelled) query.cancel(); + await server.cancelPacket; + server.reply( + pgErrorResponse({ S: "ERROR", C: "57014", M: "canceling statement due to user request" }), + pgReadyForQuery(), + ); + server.answerPrepared("discarded"); + expect(await settled).toEqual([ + "ERR_POSTGRES_SERVER_ERROR", + "ERR_POSTGRES_QUERY_CANCELLED", + "ERR_POSTGRES_QUERY_CANCELLED", + ]); + kept.push(resolved, ...cancelled); + await sql.close(); + } + + // Each round made a session and a cancel connection. GC finalizes them over a few cycles. + const deadline = performance.now() + 5_000; + Bun.gc(true); + while (connections() > before + 2 && performance.now() < deadline) { + await Bun.sleep(20); + Bun.gc(true); + } + expect(connections()).toBeLessThanOrEqual(before + 2); + expect(kept).toHaveLength(rounds * 4); +}); + // The scripted backend compares the packet with `pgCancelRequest`, which this // change also wrote. Here a real server is the judge of the bytes. describeWithContainer("postgres", { image: "postgres_plain" }, container => { From 3570e3335ed330bbde7a0ca65c12ad6e2a725c82 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 2 Oct 2026 18:07:38 +0000 Subject: [PATCH 32/34] test(sql): cancel() while only the Parse of a query is on the wire --- test/js/sql/postgres-query-cancel.test.ts | 39 +++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/test/js/sql/postgres-query-cancel.test.ts b/test/js/sql/postgres-query-cancel.test.ts index b326fbb7aa04..fedb7fd4baad 100644 --- a/test/js/sql/postgres-query-cancel.test.ts +++ b/test/js/sql/postgres-query-cancel.test.ts @@ -714,6 +714,45 @@ test("cancel() during the Parse of a statement does not fail the queries that sh expect(server.queryUnits).toBe(2); }); +// The first run of a statement with parameters sends Parse, Describe and Sync and +// waits for the parameter types. Its Bind is not written, so cancel() rejects the +// query at once and opens no connection. The backend still answers the Parse, and +// the statement is prepared for the next query with that text. +test("cancel() while only the Parse of a query is on the wire rejects it and keeps the statement", async () => { + await using server = await backend(); + server.autoReply = false; + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + const statement = (value: string) => sql`select ${value}::text as v`; + + const cancelled = statement("x").execute(); + const cancelledSettled = cancelled.then( + rows => rows, + err => err, + ); + await server.untilQueryUnits(1); + cancelled.cancel(); + const err = await cancelledSettled; + expect({ code: err.code, hint: err.hint }).toEqual({ code: "ERR_POSTGRES_QUERY_CANCELLED", hint: undefined }); + + server.reply( + pgParseComplete(), + pgParameterDescription([TEXT_OID]), + pgRowDescription([{ name: "v", typeOid: TEXT_OID }]), + pgReadyForQuery(), + ); + + // The next run needs no Parse: its unit is a Bind and an Execute. + const next = statement("z").execute(); + await server.untilQueryUnits(2); + server.answerPrepared("z"); + expect(await next).toEqual([{ v: "z" }]); + expect({ + parses: server.frontendMessages.match(/P/g)?.length, + binds: server.frontendMessages.match(/B/g)?.length, + connections: server.connections, + }).toEqual({ parses: 1, binds: 1, connections: 1 }); +}); + test("cancel() on a queued query does not cancel the one the backend is running", async () => { await using server = await backend(); server.autoReply = false; From e1c5315186eefb029a620a4fc30c7fcc203ffef0 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 2 Oct 2026 18:55:14 +0000 Subject: [PATCH 33/34] sql(postgres): shorten two comments --- src/sql_jsc/postgres/PostgresRequest.rs | 3 +-- src/sql_jsc/postgres/PostgresSQLQuery.rs | 6 +++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/sql_jsc/postgres/PostgresRequest.rs b/src/sql_jsc/postgres/PostgresRequest.rs index 1053f0a25b11..1ee4249a7d87 100644 --- a/src/sql_jsc/postgres/PostgresRequest.rs +++ b/src/sql_jsc/postgres/PostgresRequest.rs @@ -454,8 +454,7 @@ pub(crate) enum EncodeRequest<'a> { } impl PostgresSQLConnection { - /// The only caller of the batch writers above. The code of a parameter runs while its Bind is - /// encoded. If that code got `request` rejected, nothing of the batch stays in the buffer. + /// The only caller of the batch writers above. Nothing stays in the buffer for a `request` that its own parameter got rejected. pub(crate) fn encode_request( &self, global: &JSGlobalObject, diff --git a/src/sql_jsc/postgres/PostgresSQLQuery.rs b/src/sql_jsc/postgres/PostgresSQLQuery.rs index c0202fc98b9c..85572604f83b 100644 --- a/src/sql_jsc/postgres/PostgresSQLQuery.rs +++ b/src/sql_jsc/postgres/PostgresSQLQuery.rs @@ -80,9 +80,9 @@ pub struct Flags { pub(crate) simple: bool, /// Rejected while in flight: its response is skipped until `ReadyForQuery`. pub(crate) discard_response: bool, - /// Which connection counter this request is in; reset to `None` when - /// `finish_request` takes it out, so the decrement is idempotent across - /// its call sites. + /// Which connection counter this request's dispatch incremented; reset to + /// `None` when `finish_request` consumes that contribution, so the + /// decrement is idempotent across its call sites. pub(crate) counter: RequestCounter, pub(crate) result_mode: PostgresSQLQueryResultMode, } From 52e8500d7c160486d32004c2abb82e6450c17a38 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Sat, 3 Oct 2026 01:03:05 +0000 Subject: [PATCH 34/34] test(sql): close the pool of each round of the GC test with its scope --- test/js/sql/postgres-query-cancel.test.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/js/sql/postgres-query-cancel.test.ts b/test/js/sql/postgres-query-cancel.test.ts index fedb7fd4baad..0496484fdb98 100644 --- a/test/js/sql/postgres-query-cancel.test.ts +++ b/test/js/sql/postgres-query-cancel.test.ts @@ -1046,7 +1046,7 @@ test("a settled query does not keep its connection alive", async () => { for (let round = 0; round < rounds; round++) { await using server = await backend(); - const sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); + await using sql = new SQL({ url: server.url, max: 1, connectionTimeout: 5 }); const resolved = sql`select 'a'`.execute(); await resolved; server.autoReply = false; @@ -1071,7 +1071,6 @@ test("a settled query does not keep its connection alive", async () => { "ERR_POSTGRES_QUERY_CANCELLED", ]); kept.push(resolved, ...cancelled); - await sql.close(); } // Each round made a session and a cancel connection. GC finalizes them over a few cycles.