Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions docs/components/connection_pool.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
73 changes: 72 additions & 1 deletion python/tests/helpers.py
Original file line number Diff line number Diff line change
@@ -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(
Expand All @@ -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())
166 changes: 166 additions & 0 deletions python/tests/test_query_cancellation.py
Original file line number Diff line number Diff line change
@@ -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
21 changes: 21 additions & 0 deletions python/tests/test_ssl_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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)
Loading