From b2585135773b2701cee18782da561eaed2badb60 Mon Sep 17 00:00:00 2001 From: Jefferson Venceslau Date: Mon, 23 Nov 2026 14:02:59 -0300 Subject: [PATCH 1/3] Wait for every query of a failed pipeline Transaction.pipeline returned the first error from try_join_all, which drops the futures of the queries still in flight. The server runs them anyway, so nothing was gained by not waiting, and a dropped request is about to mean an abandoned query that gets a cancel request. Collect all results with join_all and return the first error. --- src/driver/transaction.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/driver/transaction.rs b/src/driver/transaction.rs index 0ff2793d..b332ce9e 100644 --- a/src/driver/transaction.rs +++ b/src/driver/transaction.rs @@ -356,7 +356,9 @@ impl Transaction { } } } - return future::try_join_all(futures).await; + // Wait for every query before returning the first error: dropping + // the ones still in flight would cancel them and close the connection. + return future::join_all(futures).await.into_iter().collect(); } Err(RustPSQLDriverError::TransactionClosedError) From 9333c6c5d9455765e6e2b615662642e6a152da8b Mon Sep 17 00:00:00 2001 From: Jefferson Venceslau Date: Mon, 23 Nov 2026 14:02:59 -0300 Subject: [PATCH 2/3] Cancel abandoned queries and close their connections When the task awaiting a query is cancelled, for example by an asyncio.wait_for timeout, pyo3 drops the Rust future. tokio-postgres has already queued the request, so the server keeps running the query, which can still commit after the caller gave up on it, and the connection goes back to the pool, where the next caller waits behind that query (#180). PoolConnection now holds its deadpool Object in a CancellableObject. Every request awaited through the Connection trait (query, query_typed, query_one, batch_execute, prepare) goes through cancel_on_drop: if the future is dropped before the request completes, a cancel request is sent from a background task, over a new connection that uses the pool's TLS connector, as asyncpg does. A connection that had a request abandoned is taken out of the pool with Object::take and closed when it is dropped, as psycopg_pool does with a connection returned while a query is active. That also covers a cancel request that cannot reach the server, and the silent network path from the issue. The next request on the same connection waits until the cancel request has been written. tokio-postgres returns before the server acts on it, so this narrows, but does not close, the window in which the cancel stops that next request instead. Cursor fetches and COPY are not covered. --- python/tests/helpers.py | 73 ++++++++++- python/tests/test_query_cancellation.py | 166 ++++++++++++++++++++++++ python/tests/test_ssl_mode.py | 21 +++ src/connection/cancel.rs | 153 ++++++++++++++++++++++ src/connection/impls.rs | 35 ++++- src/connection/mod.rs | 1 + src/connection/structs.rs | 10 +- src/driver/connection.rs | 13 +- src/driver/connection_pool.rs | 28 ++-- src/driver/connection_pool_builder.rs | 8 +- src/driver/utils.rs | 30 ++++- 11 files changed, 502 insertions(+), 36 deletions(-) create mode 100644 python/tests/test_query_cancellation.py create mode 100644 src/connection/cancel.rs diff --git a/python/tests/helpers.py b/python/tests/helpers.py index 3e1336b2..8e38142f 100644 --- a/python/tests/helpers.py +++ b/python/tests/helpers.py @@ -1,9 +1,17 @@ from __future__ import annotations +import asyncio import typing +from contextlib import asynccontextmanager + +import pytest if typing.TYPE_CHECKING: - from psqlpy import Connection, Transaction + from collections.abc import AsyncIterator, Awaitable, Callable + + from psqlpy import Connection, ConnectionPool, Transaction + +SERVER_WAIT = 5.0 async def count_rows_in_test_table( @@ -14,3 +22,66 @@ async def count_rows_in_test_table( f"SELECT COUNT(*) FROM {table_name}", ) return query_result.result()[0]["count"] + + +@asynccontextmanager +async def row_locked(psql_pool: ConnectionPool, table_name: str) -> AsyncIterator[None]: + """Hold a lock on row 1 of `table_name` from another session.""" + connection = await psql_pool.connection() + transaction = connection.transaction() + await transaction.begin() + await transaction.execute(f"SELECT id FROM {table_name} WHERE id = 1 FOR UPDATE") + try: + yield + finally: + await transaction.rollback() + connection.close() + + +async def eventually(check: Callable[[], Awaitable[bool]]) -> bool: + loop = asyncio.get_running_loop() + deadline = loop.time() + SERVER_WAIT + while loop.time() < deadline: + if await check(): + return True + await asyncio.sleep(0.05) + return False + + +async def is_running(psql_pool: ConnectionPool, query: str) -> bool: + async with psql_pool.acquire() as connection: + rows = await connection.execute( + "SELECT 1 FROM pg_stat_activity WHERE query = $1 AND state = 'active'", + [query], + ) + return bool(rows.result()) + + +async def is_not_running(psql_pool: ConnectionPool, query: str) -> bool: + return not await is_running(psql_pool, query) + + +async def abandon( + psql_pool: ConnectionPool, + query: str, + awaitable: Awaitable[object], +) -> None: + """Cancel the task awaiting `awaitable` once `query` runs on the server.""" + + async def wait() -> None: + await awaitable + + task = asyncio.create_task(wait()) + assert await eventually(lambda: is_running(psql_pool, query)) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + +async def row_exists(psql_pool: ConnectionPool, table_name: str, row_id: int) -> bool: + async with psql_pool.acquire() as connection: + rows = await connection.execute( + f"SELECT 1 FROM {table_name} WHERE id = $1", + [row_id], + ) + return bool(rows.result()) diff --git a/python/tests/test_query_cancellation.py b/python/tests/test_query_cancellation.py new file mode 100644 index 00000000..23bef21a --- /dev/null +++ b/python/tests/test_query_cancellation.py @@ -0,0 +1,166 @@ +"""A query whose awaiting task is cancelled must not keep running on the server. + +Each test makes another session lock row 1 of the default test table, so a +statement on that row waits on the server until the test gives up on it. +""" + +import asyncio +from collections.abc import AsyncGenerator + +import pytest +from psqlpy import ConnectionPool +from psqlpy.exceptions import ConnectionExecuteError + +from tests.helpers import ( + SERVER_WAIT, + abandon, + eventually, + is_not_running, + is_running, + row_exists, + row_locked, +) + +pytestmark = pytest.mark.anyio + + +@pytest.fixture +async def small_pool(dsn: str) -> AsyncGenerator[ConnectionPool, None]: + """Pool under test; the tests watch it through `psql_pool`.""" + pool = ConnectionPool(dsn=dsn, max_db_pool_size=2) + yield pool + pool.close() + + +def delete_row_1(table_name: str) -> str: + return f"DELETE FROM {table_name} WHERE id = 1" + + +async def test_timed_out_query_is_cancelled_on_server( + psql_pool: ConnectionPool, + small_pool: ConnectionPool, + table_name: str, +) -> None: + """An asyncio.wait_for timeout stops the query on the server, so nothing commits.""" + query = delete_row_1(table_name) + + async def delete() -> None: + async with small_pool.acquire() as connection: + await connection.execute(query) + + async with row_locked(psql_pool, table_name): + waiter = asyncio.create_task(asyncio.wait_for(delete(), 2)) + assert await eventually(lambda: is_running(psql_pool, query)) + with pytest.raises(asyncio.TimeoutError): + await waiter + assert await eventually(lambda: is_not_running(psql_pool, query)) + + assert await row_exists(psql_pool, table_name, 1) + + +async def test_cancelled_query_in_transaction_is_cancelled_on_server( + psql_pool: ConnectionPool, + small_pool: ConnectionPool, + table_name: str, +) -> None: + query = delete_row_1(table_name) + connection = await small_pool.connection() + transaction = connection.transaction() + await transaction.begin() + try: + async with row_locked(psql_pool, table_name): + await abandon(psql_pool, query, transaction.execute(query)) + assert await eventually(lambda: is_not_running(psql_pool, query)) + finally: + await transaction.rollback() + connection.close() + + assert await row_exists(psql_pool, table_name, 1) + + +async def test_cancelled_execute_many_is_cancelled_on_server( + psql_pool: ConnectionPool, + small_pool: ConnectionPool, + table_name: str, +) -> None: + """The statements of an abandoned batch are rolled back, not committed later.""" + query = f"DELETE FROM {table_name} WHERE id = $1" + + async def delete_rows() -> None: + async with small_pool.acquire() as connection: + await connection.execute_many(query, [[1], [2]]) + + async with row_locked(psql_pool, table_name): + await abandon(psql_pool, query, delete_rows()) + assert await eventually(lambda: is_not_running(psql_pool, query)) + + assert await row_exists(psql_pool, table_name, 1) + assert await row_exists(psql_pool, table_name, 2) + + +async def test_connection_with_cancelled_query_is_not_reused( + psql_pool: ConnectionPool, + small_pool: ConnectionPool, + table_name: str, +) -> None: + """The next acquire gets another backend, even while the row is still locked.""" + query = delete_row_1(table_name) + async with small_pool.acquire() as connection: + first_pid = await connection.fetch_val("SELECT pg_backend_pid()") + + async def delete() -> None: + async with small_pool.acquire() as connection: + await connection.execute(query) + + async with row_locked(psql_pool, table_name): + await abandon(psql_pool, query, delete()) + async with small_pool.acquire() as connection: + next_pid = await asyncio.wait_for( + connection.fetch_val("SELECT pg_backend_pid()"), + SERVER_WAIT, + ) + + assert next_pid != first_pid + + +async def test_connection_leaves_pool_after_cancelled_query( + psql_pool: ConnectionPool, + small_pool: ConnectionPool, + table_name: str, +) -> None: + """Later queries on the connection run, and closing it takes it out of the pool.""" + query = delete_row_1(table_name) + connection = await small_pool.connection() + async with row_locked(psql_pool, table_name): + await abandon(psql_pool, query, connection.execute(query)) + assert await asyncio.wait_for(connection.fetch_val("SELECT 1"), SERVER_WAIT) == 1 + + size_before_close = small_pool.status().size + connection.close() + + assert small_pool.status().size == size_before_close - 1 + + +async def test_completed_query_keeps_its_connection(small_pool: ConnectionPool) -> None: + async with small_pool.acquire() as connection: + first_pid = await connection.fetch_val("SELECT pg_backend_pid()") + async with small_pool.acquire() as connection: + second_pid = await connection.fetch_val("SELECT pg_backend_pid()") + + assert second_pid == first_pid + assert small_pool.status().size == 1 + + +async def test_failed_pipeline_keeps_its_connection(small_pool: ConnectionPool) -> None: + """A failing statement does not abandon the rest of its pipeline.""" + async with small_pool.acquire() as connection: + first_pid = await connection.fetch_val("SELECT pg_backend_pid()") + transaction = connection.transaction() + await transaction.begin() + with pytest.raises(ConnectionExecuteError): + await transaction.pipeline([("SELECT 1 / 0", []), ("SELECT 1", [])]) + await transaction.rollback() + async with small_pool.acquire() as connection: + second_pid = await connection.fetch_val("SELECT pg_backend_pid()") + + assert second_pid == first_pid diff --git a/python/tests/test_ssl_mode.py b/python/tests/test_ssl_mode.py index 4c72014e..0cc2180a 100644 --- a/python/tests/test_ssl_mode.py +++ b/python/tests/test_ssl_mode.py @@ -2,6 +2,8 @@ from psqlpy import ConnectionPool, SslMode from psqlpy._internal import ConnectionPoolBuilder +from tests.helpers import abandon, eventually, is_not_running, row_exists, row_locked + pytestmark = pytest.mark.anyio @@ -98,3 +100,22 @@ async def test_ssl_mode_require_without_ca_file( connection = await pool.connection() await connection.execute("SELECT 1") + + +async def test_cancelled_query_over_tls_is_cancelled_on_server( + psql_pool: ConnectionPool, + psql_pool_with_cert_file: ConnectionPool, + table_name: str, +) -> None: + """The cancel request negotiates TLS the way the pool's connections do.""" + query = f"DELETE FROM {table_name} WHERE id = 1" + + async def delete() -> None: + async with psql_pool_with_cert_file.acquire() as connection: + await connection.execute(query) + + async with row_locked(psql_pool, table_name): + await abandon(psql_pool, query, delete()) + assert await eventually(lambda: is_not_running(psql_pool, query)) + + assert await row_exists(psql_pool, table_name, 1) diff --git a/src/connection/cancel.rs b/src/connection/cancel.rs new file mode 100644 index 00000000..d45998ce --- /dev/null +++ b/src/connection/cancel.rs @@ -0,0 +1,153 @@ +use std::{ + future::Future, + mem::ManuallyDrop, + ops::{Deref, DerefMut}, + sync::{ + atomic::{AtomicBool, Ordering}, + Mutex, PoisonError, + }, +}; + +use deadpool_postgres::Object; +use futures::future::{BoxFuture, FutureExt, Shared}; +use tokio::task::AbortHandle; + +use crate::{driver::utils::ConfiguredTLS, runtime::tokio_runtime}; + +/// A connection checked out of the pool that cancels the queries its +/// callers abandon. +/// +/// A query is abandoned when the future awaiting it is dropped before the +/// server answers, which is what happens to a Python coroutine whose task is +/// cancelled, for example by `asyncio.wait_for`. The server keeps running the +/// query, so a cancel request is sent for it. A connection that had a query +/// abandoned is closed when it is dropped instead of going back to the pool, +/// where the next caller would wait behind that query. +pub struct CancellableObject { + // Taken in `Drop`, which decides whether it goes back to the pool. + object: ManuallyDrop, + tls: ConfiguredTLS, + abandoned: AtomicBool, + pending_cancel: Mutex>, +} + +/// A cancel request being sent to the server. +struct PendingCancel { + // Tells whether the request is still being sent without polling `sent`. + task: AbortHandle, + sent: Shared>, +} + +impl CancellableObject { + #[must_use] + pub fn new(object: Object, tls: ConfiguredTLS) -> Self { + Self { + object: ManuallyDrop::new(object), + tls, + abandoned: AtomicBool::new(false), + pending_cancel: Mutex::new(None), + } + } + + /// Await `request`, and send a cancel request for it if this future is + /// dropped before `request` completes. + pub async fn cancel_on_drop(&self, request: F) -> F::Output { + // Shrinks the window in which a cancel request meant for an abandoned + // query stops this one instead. It does not close it: tokio-postgres + // returns once the request is written, before the server acts on it. + self.wait_for_pending_cancel().await; + + let guard = CancelOnDrop(self); + let output = request.await; + std::mem::forget(guard); + output + } + + async fn wait_for_pending_cancel(&self) { + if !self.abandoned.load(Ordering::Acquire) { + return; + } + let sent = self + .pending_cancel + .lock() + .unwrap_or_else(PoisonError::into_inner) + .as_ref() + .map(|pending| pending.sent.clone()); + if let Some(sent) = sent { + sent.await; + } + } + + fn request_cancel(&self) { + self.abandoned.store(true, Ordering::Release); + + let mut pending_cancel = self + .pending_cancel + .lock() + .unwrap_or_else(PoisonError::into_inner); + // The server cancels whatever the connection runs when the request + // arrives. Queries abandoned together, like the statements of an + // `execute_many`, are covered by one request. + if pending_cancel + .as_ref() + .is_some_and(|pending| !pending.task.is_finished()) + { + return; + } + + let token = self.object.cancel_token(); + let tls = self.tls.clone(); + let task = tokio_runtime().spawn(async move { + // Best effort: when the request cannot be sent, the query keeps + // running, and the connection is still closed when it is dropped. + let _ = tls.cancel_query(token).await; + }); + *pending_cancel = Some(PendingCancel { + task: task.abort_handle(), + sent: task.map(|_| ()).boxed().shared(), + }); + } +} + +impl Deref for CancellableObject { + type Target = Object; + + fn deref(&self) -> &Object { + &self.object + } +} + +impl DerefMut for CancellableObject { + fn deref_mut(&mut self) -> &mut Object { + &mut self.object + } +} + +impl Drop for CancellableObject { + fn drop(&mut self) { + // SAFETY: `object` is private to this type, taken only here, and + // `drop` runs once. + let object = unsafe { ManuallyDrop::take(&mut self.object) }; + if *self.abandoned.get_mut() { + drop(Object::take(object)); + } + } +} + +impl std::fmt::Debug for CancellableObject { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CancellableObject") + .field("object", &*self.object) + .field("abandoned", &self.abandoned) + .finish_non_exhaustive() + } +} + +/// Sends a cancel request when dropped; forgotten once the request completes. +struct CancelOnDrop<'a>(&'a CancellableObject); + +impl Drop for CancelOnDrop<'_> { + fn drop(&mut self) { + self.0.request_cancel(); + } +} diff --git a/src/connection/impls.rs b/src/connection/impls.rs index e8034fd4..4108a919 100644 --- a/src/connection/impls.rs +++ b/src/connection/impls.rs @@ -181,10 +181,16 @@ impl CloseTransaction for SingleConnection { impl Connection for PoolConnection { async fn prepare(&self, query: &str, prepared: bool) -> PSQLPyResult { if prepared { - return Ok(self.connection.prepare_cached(query).await?); + return Ok(self + .connection + .cancel_on_drop(self.connection.prepare_cached(query)) + .await?); } - let prepared = self.connection.prepare(query).await?; + let prepared = self + .connection + .cancel_on_drop(self.connection.prepare(query)) + .await?; self.drop_prepared(&prepared).await?; Ok(prepared) } @@ -192,7 +198,10 @@ impl Connection for PoolConnection { async fn drop_prepared(&self, stmt: &Statement) -> PSQLPyResult<()> { let deallocate_query = format!("DEALLOCATE PREPARE {}", stmt.name()); - Ok(self.connection.batch_execute(&deallocate_query).await?) + Ok(self + .connection + .cancel_on_drop(self.connection.batch_execute(&deallocate_query)) + .await?) } async fn query( @@ -203,7 +212,10 @@ impl Connection for PoolConnection { where T: ?Sized + ToStatement, { - Ok(self.connection.query(statement, params).await?) + Ok(self + .connection + .cancel_on_drop(self.connection.query(statement, params)) + .await?) } async fn query_typed( @@ -211,11 +223,17 @@ impl Connection for PoolConnection { statement: &str, params: &[(&(dyn postgres_types::ToSql + Sync), postgres_types::Type)], ) -> PSQLPyResult> { - Ok(self.connection.query_typed(statement, params).await?) + Ok(self + .connection + .cancel_on_drop(self.connection.query_typed(statement, params)) + .await?) } async fn batch_execute(&self, query: &str) -> PSQLPyResult<()> { - Ok(self.connection.batch_execute(query).await?) + Ok(self + .connection + .cancel_on_drop(self.connection.batch_execute(query)) + .await?) } async fn query_one( @@ -226,7 +244,10 @@ impl Connection for PoolConnection { where T: ?Sized + ToStatement, { - Ok(self.connection.query_one(statement, params).await?) + Ok(self + .connection + .cancel_on_drop(self.connection.query_one(statement, params)) + .await?) } } diff --git a/src/connection/mod.rs b/src/connection/mod.rs index c8f176fa..f88f388d 100644 --- a/src/connection/mod.rs +++ b/src/connection/mod.rs @@ -1,3 +1,4 @@ +pub mod cancel; pub mod impls; pub mod structs; pub mod traits; diff --git a/src/connection/structs.rs b/src/connection/structs.rs index f28f8abc..9da82a45 100644 --- a/src/connection/structs.rs +++ b/src/connection/structs.rs @@ -5,6 +5,10 @@ use deadpool_postgres::Object; use postgres_types::Type; use tokio_postgres::{Client, Config, Statement}; +use crate::driver::utils::ConfiguredTLS; + +use super::cancel::CancellableObject; + /// Per-connection cache for COPY column-type introspection results. /// Key: `(schema_name, table_name, columns_in_declaration_order)`. /// Column order is significant: `["a","b"]` and `["b","a"]` produce different COPY targets. @@ -14,7 +18,7 @@ pub type CopyTypeCache = DashMap<(Option, String, Vec), Vec, @@ -24,9 +28,9 @@ pub struct PoolConnection { impl PoolConnection { #[must_use] - pub fn new(connection: Object, pg_config: Arc) -> Self { + pub fn new(connection: Object, pg_config: Arc, tls: ConfiguredTLS) -> Self { Self { - connection, + connection: CancellableObject::new(connection, tls), in_transaction: false, in_cursor: false, pg_config, diff --git a/src/driver/connection.rs b/src/driver/connection.rs index 7cdc503f..e1cba658 100644 --- a/src/driver/connection.rs +++ b/src/driver/connection.rs @@ -15,7 +15,7 @@ use crate::{ runtime::tokio_runtime, }; -use super::{connection_pool::connect_pool, transaction::Transaction}; +use super::{connection_pool::connect_pool, transaction::Transaction, utils::ConfiguredTLS}; /// Make new connection pool. /// @@ -115,7 +115,8 @@ pub async fn connect( #[derive(Clone, Debug)] pub struct Connection { pub conn: Option>>, - db_pool: Option, + /// Pool to check a connection out of, with the TLS its cancel requests use. + db_pool: Option<(Pool, ConfiguredTLS)>, pub pg_config: Arc, } @@ -123,7 +124,7 @@ impl Connection { #[must_use] pub fn new( conn: Option>>, - db_pool: Option, + db_pool: Option<(Pool, ConfiguredTLS)>, pg_config: Arc, ) -> Self { Connection { @@ -140,7 +141,7 @@ impl Connection { #[must_use] pub fn db_pool(&self) -> Option { - self.db_pool.clone() + self.db_pool.as_ref().map(|(pool, _)| pool.clone()) } } @@ -172,7 +173,7 @@ impl Connection { return Ok(self_); } - if let Some(db_pool) = db_pool { + if let Some((db_pool, tls)) = db_pool { let connection = tokio_runtime() .spawn(async move { Ok::(db_pool.get().await?) @@ -181,7 +182,7 @@ impl Connection { pyo3::Python::attach(|gil| { let mut self_ = self_.borrow_mut(gil); self_.conn = Some(Arc::new(RwLock::new(PSQLPyConnection::PoolConn( - PoolConnection::new(connection, pg_config), + PoolConnection::new(connection, pg_config, tls), )))); }); return Ok(self_); diff --git a/src/driver/connection_pool.rs b/src/driver/connection_pool.rs index 1f725e61..8645c8f6 100644 --- a/src/driver/connection_pool.rs +++ b/src/driver/connection_pool.rs @@ -17,7 +17,7 @@ use crate::{ use super::{ connection::Connection, listener::core::Listener, - utils::{build_connection_config, build_manager, build_tls}, + utils::{build_connection_config, build_manager, build_tls, ConfiguredTLS}, }; #[derive(Debug, Clone)] @@ -144,11 +144,8 @@ pub fn connect_pool( }; } - let mgr: Manager = build_manager( - mgr_config, - pg_config.clone(), - build_tls(&ca_file, &ssl_mode)?, - ); + let tls = build_tls(&ca_file, &ssl_mode)?; + let mgr: Manager = build_manager(mgr_config, pg_config.clone(), tls.clone()); let mut db_pool_builder = Pool::builder(mgr); if let Some(max_db_pool_size) = max_db_pool_size { @@ -158,7 +155,7 @@ pub fn connect_pool( let pool = db_pool_builder.build()?; Ok(ConnectionPool::build( - pool, pg_config, ca_file, ssl_mode, None, + pool, pg_config, ca_file, ssl_mode, None, tls, )) } @@ -226,6 +223,7 @@ pub struct ConnectionPool { pool: Pool, pg_config: Arc, pool_conf: ConnectionPoolConf, + tls: ConfiguredTLS, } impl ConnectionPool { @@ -236,11 +234,13 @@ impl ConnectionPool { ca_file: Option, ssl_mode: Option, prepare: Option, + tls: ConfiguredTLS, ) -> Self { ConnectionPool { pool, pg_config: Arc::new(pg_config), pool_conf: ConnectionPoolConf::new(ca_file, ssl_mode, prepare.unwrap_or(true)), + tls, } } @@ -253,7 +253,7 @@ impl ConnectionPool { Ok(Connection::new( Some(Arc::new(RwLock::new(PSQLPyConnection::PoolConn( - PoolConnection::new(connection, self.pg_config.clone()), + PoolConnection::new(connection, self.pg_config.clone(), self.tls.clone()), )))), None, self.pg_config.clone(), @@ -399,7 +399,11 @@ impl ConnectionPool { #[must_use] pub fn acquire(&self) -> Connection { - Connection::new(None, Some(self.pool.clone()), self.pg_config.clone()) + Connection::new( + None, + Some((self.pool.clone(), self.tls.clone())), + self.pg_config.clone(), + ) } #[must_use] @@ -418,9 +422,9 @@ impl ConnectionPool { /// # Errors /// May return Err Result if cannot get new connection from the pool. pub async fn connection(self_: pyo3::Py) -> PSQLPyResult { - let (db_pool, pg_config) = pyo3::Python::attach(|gil| { + let (db_pool, pg_config, tls) = pyo3::Python::attach(|gil| { let slf = self_.borrow(gil); - (slf.pool.clone(), slf.pg_config.clone()) + (slf.pool.clone(), slf.pg_config.clone(), slf.tls.clone()) }); let connection = tokio_runtime() .spawn(async move { @@ -430,7 +434,7 @@ impl ConnectionPool { Ok(Connection::new( Some(Arc::new(RwLock::new(PSQLPyConnection::PoolConn( - PoolConnection::new(connection, pg_config.clone()), + PoolConnection::new(connection, pg_config.clone(), tls), )))), None, pg_config, diff --git a/src/driver/connection_pool_builder.rs b/src/driver/connection_pool_builder.rs index 78cc97af..d4eaf3cb 100644 --- a/src/driver/connection_pool_builder.rs +++ b/src/driver/connection_pool_builder.rs @@ -54,11 +54,8 @@ impl ConnectionPoolBuilder { }; } - let mgr: Manager = build_manager( - mgr_config, - self.config.clone(), - build_tls(&self.ca_file, &self.ssl_mode)?, - ); + let tls = build_tls(&self.ca_file, &self.ssl_mode)?; + let mgr: Manager = build_manager(mgr_config, self.config.clone(), tls.clone()); let mut db_pool_builder = Pool::builder(mgr); if let Some(max_db_pool_size) = self.max_db_pool_size { @@ -73,6 +70,7 @@ impl ConnectionPoolBuilder { self.ca_file.clone(), self.ssl_mode, self.prepare, + tls, )) } diff --git a/src/driver/utils.rs b/src/driver/utils.rs index 91ceb152..22e87b81 100644 --- a/src/driver/utils.rs +++ b/src/driver/utils.rs @@ -1,10 +1,10 @@ -use std::{str::FromStr, time::Duration}; +use std::{fmt, str::FromStr, time::Duration}; use deadpool_postgres::{Manager, ManagerConfig}; use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode}; use postgres_openssl::MakeTlsConnector; use pyo3::{types::PyAnyMethods, Py, PyAny, Python}; -use tokio_postgres::{Config, NoTls}; +use tokio_postgres::{CancelToken, Config, NoTls}; use crate::{ exceptions::rust_errors::{PSQLPyResult, RustPSQLDriverError}, @@ -171,11 +171,37 @@ pub fn build_connection_config( Ok(pg_config) } +#[derive(Clone)] pub enum ConfiguredTLS { NoTls, TlsConnector(MakeTlsConnector), } +impl fmt::Debug for ConfiguredTLS { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ConfiguredTLS::NoTls => f.write_str("NoTls"), + ConfiguredTLS::TlsConnector(_) => f.write_str("TlsConnector"), + } + } +} + +impl ConfiguredTLS { + /// Ask the server to cancel the query running on the connection of `token`. + /// + /// The cancel request goes over a new connection that negotiates TLS the + /// same way the original connection did. + /// + /// # Errors + /// May return Err Result if cannot connect to the server. + pub async fn cancel_query(self, token: CancelToken) -> Result<(), tokio_postgres::Error> { + match self { + ConfiguredTLS::NoTls => token.cancel_query(NoTls).await, + ConfiguredTLS::TlsConnector(connector) => token.cancel_query(connector).await, + } + } +} + /// Create TLS. /// /// # Errors From cabe6f2e9e290a779f7e6b9a9e330e9a7cde6a39 Mon Sep 17 00:00:00 2001 From: Jefferson Venceslau Date: Mon, 23 Nov 2026 14:03:06 -0300 Subject: [PATCH 3/3] Document what happens to a query whose task is cancelled --- docs/components/connection_pool.md | 42 ++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/docs/components/connection_pool.md b/docs/components/connection_pool.md index b731135f..ed8f5094 100644 --- a/docs/components/connection_pool.md +++ b/docs/components/connection_pool.md @@ -153,6 +153,48 @@ async def main() -> None: # ConnectionPool is closed ``` +### Cancel a query with a timeout +When the task awaiting a query is cancelled, for example by `asyncio.wait_for`, +`PSQLPy` sends a cancel request to the server, over a new connection with +the same TLS settings as the pool, and the server stops the query. +The connection that ran it does not go back to the pool: +when it is released, it is closed, and the pool opens a new one on the next request. + +Release the connection after a timeout instead of running more queries on it. +A cancelled `execute_many` leaves its transaction open on that connection, +and the cancel request can still reach the server after the next query has started. + +This applies to the queries of a `Connection`, a `Transaction` and a `PreparedStatement` +taken from a `ConnectionPool`: `execute`, `execute_batch`, `execute_many`, `fetch`, +`fetch_row`, `fetch_val`, `prepare`, `pipeline` and the transaction statements. +Cursors and the COPY methods do not cancel their queries yet. + +```python +import asyncio + +from psqlpy import ConnectionPool + + +async def main() -> None: + db_pool = ConnectionPool(dsn="postgres://postgres:postgres@localhost:5432/postgres") + async with db_pool.acquire() as connection: + try: + await asyncio.wait_for( + connection.execute("SELECT pg_sleep(60)"), + timeout=1, + ) + except asyncio.TimeoutError: + ... # the query was cancelled on the server +``` + +::: warning +Cancellation is a race. If the query finishes on the server before the cancel request +arrives, its effects stay, even though your code saw a timeout, +and the cancel request stops the next query on that connection if one is already running. +If the cancel request cannot reach the server, the query may keep running there until it ends. +In every case, the connection is closed when it is released. +::: + ## Connection pool methods ### Resize