Skip to content

Repeated cancellation during asyncpg connection recycling leaks a pool slot #13622

Closed

Description

@CaselIT

Discussed in #13620

Originally posted by cooper-oai September 30, 2026

Describe the bug

Cancelling an engine.connect() task twice while it recycles an existing asyncpg connection can permanently consume a pool slot. After the task finishes, the driver connection is closed, but the pool still reports one checked-out connection. With a one-slot pool, the next checkout times out.

A single cancellation at the same point returns the slot correctly. This example uses standard asyncio, not AnyIO or an alternate event loop.

Versions

  • SQLAlchemy 2.0.54, and current main at bc8982869d887a47a535ba45d80eb9a6f4595530 (reports 2.1.2).
  • asyncpg 0.31.0; greenlet 3.5.6.
  • CPython 3.12.13.
  • PostgreSQL 16.15.
  • Linux x86_64.

To reproduce

Use a disposable PostgreSQL instance. For example:

docker run --rm --name sqlalchemy-recycle-repro \
  -e POSTGRES_HOST_AUTH_METHOD=trust \
  -p 127.0.0.1:55484:5432 postgres:16

Once PostgreSQL is ready, install the dependencies in a virtual environment:

python -m pip install 'SQLAlchemy[asyncio]==2.0.54' 'asyncpg==0.31.0' 'greenlet==3.5.6'
python reproduce.py --cancels 2
python reproduce.py --cancels 1
python reproduce.py --cancels 0

Alternatively, set DATABASE_URL to a local test database URL using the postgresql+asyncpg scheme. The recorded runs used a local PostgreSQL 16.15 server, rather than the Docker command above.

The connection subclass pauses a live connection's close so the first cancellation lands during recycling. It then reports the second close attempt, allowing another cancellation during failed-checkout cleanup. It does not patch SQLAlchemy, replace driver termination, or pause the close of an already-closed connection.

Save this as reproduce.py:

import argparse
import asyncio
import gc
import os
import platform

import asyncpg
import sqlalchemy
from sqlalchemy import text
from sqlalchemy.ext.asyncio import create_async_engine


class CloseBarrierConnection(asyncpg.Connection):
    close_calls = None
    release_close = None

    async def close(self, *, timeout=None):
        if self.close_calls is not None:
            self.close_calls.put_nowait(self.is_closed())
            if not self.is_closed():
                await self.release_close.wait()
        return await super().close(timeout=timeout)


async def main(cancels):
    print(
        f"Python {platform.python_version()}, "
        f"SQLAlchemy {sqlalchemy.__version__}, asyncpg {asyncpg.__version__}",
        flush=True,
    )
    engine = create_async_engine(
        os.environ.get(
            "DATABASE_URL",
            "postgresql+asyncpg://postgres@127.0.0.1:55484/postgres",
        ),
        pool_size=1,
        max_overflow=0,
        pool_timeout=0.1,
        pool_recycle=0.01,
        connect_args={"connection_class": CloseBarrierConnection},
    )
    try:
        async with engine.connect() as connection:
            assert await connection.scalar(text("select 1")) == 1
            driver = (await connection.get_raw_connection()).driver_connection
        await asyncio.sleep(0.05)  # Make the next checkout recycle this connection.

        calls = CloseBarrierConnection.close_calls = asyncio.Queue()
        release = CloseBarrierConnection.release_close = asyncio.Event()

        async def checkout():
            async with engine.connect() as connection:
                assert await connection.scalar(text("select 1")) == 1

        task = asyncio.create_task(checkout())
        try:
            async with asyncio.timeout(5):
                assert await calls.get() is False  # Recycling a live connection.
                if cancels:
                    task.cancel()
                    assert await calls.get() is True  # Cleanup retries close.
                    if cancels == 2:
                        task.cancel()
                else:
                    release.set()
                try:
                    await task
                except asyncio.CancelledError:
                    assert cancels
        finally:
            release.set()
            if not task.done():
                task.cancel()
                await asyncio.gather(task, return_exceptions=True)
        await asyncio.sleep(0)  # Let the shielded close finish.
        await asyncio.sleep(0)
        gc.collect()

        print(f"cancels={cancels}; original driver closed={driver.is_closed()}")
        print(f"checkout task finished={task.done()}; cancelled={task.cancelled()}")
        print(engine.pool.status(), flush=True)
        async with engine.connect() as connection:
            print("probe:", await connection.scalar(text("select 1")), flush=True)
    finally:
        CloseBarrierConnection.close_calls = None
        await engine.dispose()


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--cancels", type=int, choices=(0, 1, 2), default=2)
    asyncio.run(main(parser.parse_args().cancels))

Results

On both 2.0.54 and the main commit above, two cancellations leave the pool exhausted:

cancels=2; original driver closed=True
checkout task finished=True; cancelled=True
Pool size: 1  Connections in pool: 0 Current Overflow: 0 Current Checked out connections: 1
sqlalchemy.exc.TimeoutError: QueuePool limit of size 1 overflow 0 reached, connection timed out, timeout 0.10

With --cancels 1, both versions return the slot and the probe succeeds:

cancels=1; original driver closed=True
checkout task finished=True; cancelled=True
Pool size: 1  Connections in pool: 1 Current Overflow: 0 Current Checked out connections: 0
probe: 1

The --cancels 0 control also passes on 2.0.54. The script waits for the checkout task to finish, releases the close barrier, and runs garbage collection before checking pool state.

Error

Full final traceback from main, with installation paths shortened:

Traceback (most recent call last):
  File "reproduce.py", line 92, in <module>
    asyncio.run(main(parser.parse_args().cancels))
  File "python3.12/asyncio/runners.py", line 195, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "python3.12/asyncio/runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "python3.12/asyncio/base_events.py", line 691, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "reproduce.py", line 82, in main
    async with engine.connect() as connection:
               ^^^^^^^^^^^^^^^^
  File "lib/sqlalchemy/ext/asyncio/base.py", line 121, in __aenter__
    return await self.start(is_ctxmanager=True)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "lib/sqlalchemy/ext/asyncio/engine.py", line 283, in start
    await greenlet_spawn(self.sync_engine.connect)
  File "lib/sqlalchemy/util/concurrency.py", line 210, in greenlet_spawn
    result = context.throw(*sys.exc_info())
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "lib/sqlalchemy/engine/base.py", line 3260, in connect
    return self._connection_cls(self)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "lib/sqlalchemy/engine/base.py", line 149, in __init__
    self._dbapi_connection = engine.raw_connection()
                             ^^^^^^^^^^^^^^^^^^^^^^^
  File "lib/sqlalchemy/engine/base.py", line 3284, in raw_connection
    return self.pool.connect()
           ^^^^^^^^^^^^^^^^^^^
  File "lib/sqlalchemy/pool/base.py", line 445, in connect
    return _ConnectionFairy._checkout(self)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "lib/sqlalchemy/pool/base.py", line 1287, in _checkout
    fairy = _ConnectionRecord.checkout(pool)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "lib/sqlalchemy/pool/base.py", line 709, in checkout
    rec = pool._do_get()
          ^^^^^^^^^^^^^
  File "lib/sqlalchemy/pool/impl.py", line 165, in _do_get
    raise exc.TimeoutError(
sqlalchemy.exc.TimeoutError: QueuePool limit of size 1 overflow 0 reached, connection timed out, timeout 0.10 (Background on this error at: https://sqlalche.me/e/21/3o7r)

Each cancellation also logs the following termination traceback on main:

Exception terminating connection <AdaptedConnection <__main__.CloseBarrierConnection object at 0x7ea210dd64e0>>
Traceback (most recent call last):
  File "lib/sqlalchemy/pool/base.py", line 370, in _close_connection
    self._dialect.do_terminate(connection)
  File "lib/sqlalchemy/dialects/postgresql/asyncpg.py", line 1171, in do_terminate
    dbapi_connection.terminate()
  File "lib/sqlalchemy/connectors/asyncio.py", line 440, in terminate
    await_(asyncio.shield(self._terminate_graceful_close()))
  File "lib/sqlalchemy/util/concurrency.py", line 167, in await_
    return current.parent.switch(awaitable)  # type: ignore[no-any-return]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "lib/sqlalchemy/util/concurrency.py", line 205, in greenlet_spawn
    value = await result
            ^^^^^^^^^^^^
asyncio.exceptions.CancelledError

Additional context

The failure appears to be in the pool's failed-checkout cleanup:

  1. Recycling calls _ConnectionRecord.__close(terminate=True). Cancellation propagates out of termination before __close() clears dbapi_connection.
  2. _ConnectionRecord.checkout() catches the first cancellation and calls _checkin_failed().
  3. _checkin_failed() calls invalidate() before checkin(). The second cancellation interrupts that invalidation, so checkin() is skipped.
  4. This occurs before checkout creates a _ConnectionFairy, leaving no fairy to return the missing record.

The physical driver connection is closed; the observable failure is lost pool capacity. This seems distinct from #12710, which concerns cancellation after synchronous connection creation completes but before AsyncConnection.start() assigns the result.

Would you accept a fix and regression test for this path? The intended behavior is to preserve cancellation while returning the failed checkout's pool slot exactly once, without making a terminated connection reusable.

Activity

  1. added this to the 2.0.x milestone on Sep 30, 2026
  2. added
    bug
    on Sep 30, 2026
  3. sqla-tester commented on Sep 30, 2026

    @sqla-tester
    Collaborator

    Mike Bayer has proposed a fix for this issue in the main branch:

    wait for async context manager close when cancelled https://gerrit.sqlalchemy.org/c/sqlalchemy/sqlalchemy/+/7004

  4. sqla-tester commented on Sep 30, 2026

    @sqla-tester
    Collaborator

    Mike Bayer has proposed a fix for this issue in the rel_2_0 branch:

    wait for async context manager close when cancelled https://gerrit.sqlalchemy.org/c/sqlalchemy/sqlalchemy/+/7005

  5. added a commit that references this issue on Sep 30, 2026
    28bb9a7
  6. added a commit that references this issue on Oct 2, 2026
    6f89987
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    asynciobugconnection pool

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions