Skip to content

fix: cancel abandoned queries and close their connections - #183

Open
z22092 wants to merge 3 commits into
psqlpy-python:mainfrom
z22092:fix/cancel-query-on-drop
Open

z22092 wants to merge 3 commits into
psqlpy-python:mainfrom
z22092:fix/cancel-query-on-drop

Conversation

@z22092

@z22092 z22092 commented Nov 23, 2026

Copy link
Copy Markdown

Description

When the task awaiting a query is cancelled (an asyncio.wait_for timeout, task.cancel()), pyo3 drops the Rust future, but tokio-postgres has already queued the request. The server keeps running the query and can commit it later, and the connection goes back to the pool while it is still busy, so the next caller waits behind it.

Changes:

  • PoolConnection holds its deadpool Object in a new CancellableObject (src/connection/cancel.rs). 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.
  • The cancel request uses the pool's TLS connector. build_tls runs once, and its ConfiguredTLS is kept on ConnectionPool, on Connection (inside db_pool) and on the connection itself.
  • A connection that had a request abandoned is taken out of the pool with Object::take and closed when it is released, instead of being handed to the next caller. This also covers a cancel request that cannot reach the server.
  • The next request on that connection waits until the cancel request has been written.
  • Transaction.pipeline now waits for every query before returning the first error (join_all instead of try_join_all). Otherwise a failing statement would abandon the queries still in flight and close the connection.
  • docs/components/connection_pool.md documents the behaviour.

Not covered: cursor fetches and the COPY methods still await their requests directly. The docs say so.

Known limitation: CancelToken::cancel_query in tokio-postgres returns once the cancel request is written (cancel_query_raw does write_all, flush and shutdown, without reading until the server closes the socket). If the abandoned query had already finished, the cancel request can still stop the next query on that connection. The docs recommend releasing the connection after a timeout. asyncpg avoids this by waiting for the server to close the cancel connection; doing the same here would need a change in tokio-postgres.

Motivation and Context

Closes #180.

How has this been tested?

  • python/tests/test_query_cancellation.py (7 tests) and one TLS test in test_ssl_mode.py. Each one holds a row lock from another session, so a statement waits on the server. It cancels the awaiting task once pg_stat_activity shows the statement active, then checks the server and the pool. On main, 6 of these 8 fail. The other two, test_completed_query_keeps_its_connection and test_failed_pipeline_keeps_its_connection, pass there and guard against regressions.
  • The TLS test fails if the cancel request is sent with NoTls instead of the pool's connector.
  • The full suite, test_ssl_mode.py included: 282 passed against PostgreSQL 18.7 with SSL on, Python 3.13. Not run locally on PostgreSQL 14 to 17 or other Python versions.
  • cargo fmt with the CI config, and clippy with the CI flags: clean. Locally this needed -A unknown-lints, because clippy 1.93 does not know clippy::unused_async_trait_impl, which the code already uses. ruff check, ruff format --check and mypy python: clean.
  • The reproduction script from the issue, with a 0.5 s pause before reading pg_stat_activity.

Before (main):

DELETE, wait_for 1 s: TimeoutError
  pool size=1 available=1
  the DELETE on the server: [{'state': 'active', 'wait_event_type': 'Lock'}]
SELECT 1, wait_for 3 s: TimeoutError
  pool size=1 available=1
SELECT 1 after the lock is released: [{'one': 1}]
  pool size=1 available=1
rows left: [{'id': 2}]

After:

DELETE, wait_for 1 s: TimeoutError
  pool size=0 available=0
  the DELETE on the server: []
SELECT 1, wait_for 3 s: [{'one': 1}]
  pool size=1 available=1
SELECT 1 after the lock is released: [{'one': 1}]
  pool size=1 available=1
rows left: [{'id': 1}, {'id': 2}]

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)

Checklist:

  • My code follows the code style of this project.
  • My change requires a change to the documentation.
  • I have updated the documentation accordingly.

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.
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 (psqlpy-python#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.
@z22092
z22092 marked this pull request as ready for review November 23, 2026 17:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A cancelled query keeps running on the server and its connection is handed out again

1 participant