#12710·sqlalchemy

add extra shielding to async connection create

Author: zzzeekCreated Jul 2, 2025Updated Sep 25, 2026
Labelsbugengineasyncioopen for pull requests

Discussed in https://github.com/sqlalchemy/sqlalchemy/discussions/12709

Locally I can only reproduce this using a trusted connection against a PG database running in a local container, which I can run like this:

podman run -d --rm -e POSTGRES_HOST_AUTH_METHOD=trust -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres -p 5433:5432 postgres:17

Script is then from the discussion (note the port 5433 which is to avoid my already running PG database):

python
import asyncio
import random
import gc
import logging

from sqlalchemy import text
from sqlalchemy.pool import NullPool
from sqlalchemy.ext.asyncio import create_async_engine

logging.basicConfig(level=logging.INFO)
logging.getLogger("sqlalchemy.pool").setLevel("DEBUG")
logger = logging.getLogger(__name__)


engine = create_async_engine("postgresql+asyncpg://postgres:postgres@localhost:5433/postgres")

async def create_connections() -> None:
    try:
        for i in range(50):
            awaitable = engine.connect()
            async with awaitable as conn:
                result = await conn.execute(text("SELECT 1"))
                result.close()

    except asyncio.CancelledError:
        logger.info("task cancelled")
        raise


async def main() -> None:
    i = 0
    for j in range(5):
        i += 1
        task = asyncio.create_task(create_connections(), name=f"task_{i}")
        await asyncio.sleep(.01)
        task.cancel()
        try:
            await task
        except asyncio.CancelledError:
            pass

    await engine.dispose()
    logger.info("done")


if __name__ == "__main__":
    asyncio.run(main())

script is then run with warnings enabled

python -Walways test3.py 

running the script half a dozen times typically to see the issue, what we will see is that when the dispose() occurs, some connections didn't get "closed" or even connected to the pool because the cancellation happened after the connection was created but before the start() method could return it - so this connection is orphaned:

INFO:sqlalchemy.pool.impl.AsyncAdaptedQueuePool:Pool disposed. Pool size: 5  Connections in pool: 0 Current Overflow: -5 Current Checked out connections: 0
INFO:sqlalchemy.pool.impl.AsyncAdaptedQueuePool:Pool recreating
INFO:__main__:done
DEBUG:sqlalchemy.pool.impl.AsyncAdaptedQueuePool:Connection <AdaptedConnection <asyncpg.connection.Connection object at 0x7f855e2225d0>> being returned to pool
DEBUG:sqlalchemy.pool.impl.AsyncAdaptedQueuePool:Connection <AdaptedConnection <asyncpg.connection.Connection object at 0x7f855e2225d0>> reset, transaction already reset
<sys>:0: ResourceWarning: unclosed <socket.socket fd=6, family=10, type=1, proto=6, laddr=('::1', 49250, 0, 0), raddr=('::1', 5433, 0, 0)>
ResourceWarning: Enable tracemalloc to get the object allocation traceback
/usr/lib64/python3.13/asyncio/selector_events.py:869: ResourceWarning: unclosed transport <_SelectorSocketTransport fd=6>
  _warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
ResourceWarning: Enable tracemalloc to get the object allocation traceback
/home/classic/.venv3/lib64/python3.13/site-packages/asyncpg/connection.py:135: ResourceWarning: unclosed connection <asyncpg.connection.Connection object at 0x7f855e2225d0>; run in asyncio debug mode to show the traceback of connection origin
  warnings.warn(msg, ResourceWarning)

we can improve the situation like this:

diff
diff --git a/lib/sqlalchemy/ext/asyncio/engine.py b/lib/sqlalchemy/ext/asyncio/engine.py
index d4ecbdac9..6e2ce9ac7 100644
--- a/lib/sqlalchemy/ext/asyncio/engine.py
+++ b/lib/sqlalchemy/ext/asyncio/engine.py
@@ -271,7 +271,7 @@ class AsyncConnection(
         if self.sync_connection:
             raise exc.InvalidRequestError("connection is already started")
         self.sync_connection = self._assign_proxied(
-            await greenlet_spawn(self.sync_engine.connect)
+            await asyncio.shield(greenlet_spawn(self.sync_engine.connect))
         )
         return self
 

then we usually get the pool weakref warning:

ERROR:sqlalchemy.pool.impl.AsyncAdaptedQueuePool:The garbage collector is trying to clean up non-checked-in connection <AdaptedConnection <asyncpg.connection.Connection object at 0x7fb58e9767b0>>, which will be terminated.  Please ensure that SQLAlchemy pooled connections are returned to the pool explicitly, either by calling ``close()`` or by using appropriate context managers to manage their lifecycle.
/usr/lib64/python3.13/asyncio/base_events.py:2019: SAWarning: The garbage collector is trying to clean up non-checked-in connection <AdaptedConnection <asyncpg.connection.Connection object at 0x7fb58e9767b0>>, which will be terminated.  Please ensure that SQLAlchemy pooled connections are returned to the pool explicitly, either by calling ``close()`` or by using appropriate context managers to manage their lifecycle.
  handle = self._ready.popleft()

but that connection is still leaking out, and we also still get the ResourceWarning version sometimes too (not sure how).

The most I can do is the patch below, which makes the error a lot less frequent, but it still happens sometimes

diff
diff --git a/lib/sqlalchemy/ext/asyncio/engine.py b/lib/sqlalchemy/ext/asyncio/engine.py
index d4ecbdac9..f87e9e683 100644
--- a/lib/sqlalchemy/ext/asyncio/engine.py
+++ b/lib/sqlalchemy/ext/asyncio/engine.py
@@ -270,9 +270,21 @@ class AsyncConnection(
         """
         if self.sync_connection:
             raise exc.InvalidRequestError("connection is already started")
-        self.sync_connection = self._assign_proxied(
-            await greenlet_spawn(self.sync_engine.connect)
-        )
+
+        conn = None
+        async def safe_connect():
+            nonlocal conn
+            conn = await greenlet_spawn(self.sync_engine.connect)
+            return conn
+
+        try:
+            awaited_conn = await asyncio.shield(safe_connect())
+        except asyncio.CancelledError:
+            if conn is not None:
+                await asyncio.shield(greenlet_spawn(conn.close))
+            raise
+
+        self.sync_connection = self._assign_proxied(awaited_conn)
         return self
 
     @property

so above, that definitely handles the issue within start(), but I still can see some cases where the connection is not checked in by the time we get to dispose(). can't really trace it out fully