From 9eb87f47aeb591fd9d354bd9b3d2918d561e6011 Mon Sep 17 00:00:00 2001 From: Federico Caselli Date: Fri, 17 Jan 2025 21:16:51 +0100 Subject: [PATCH] asyncpg: shield connection close in terminate to avoid connection leak Added an additional ``shield()`` call within the connection terminate process of the asyncpg driver, to mitigate an issue where terminate would be prevented from completing under the anyio concurrency library. Fixes #12077 Closes: #12076 Pull-request: https://github.com/sqlalchemy/sqlalchemy/pull/12076 Pull-request-sha: 6ae261ea7668f4c850874666efec6fef658b08c0 Change-Id: Iaec63d02b620201dc60ffdad76ba9d61d427cac1 (cherry picked from commit 2f6ca6554ddd725849dd6b2d32bf495391087bec) --- doc/build/changelog/unreleased_20/12077.rst | 7 +++++++ lib/sqlalchemy/dialects/postgresql/asyncpg.py | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) create mode 100644 doc/build/changelog/unreleased_20/12077.rst diff --git a/doc/build/changelog/unreleased_20/12077.rst b/doc/build/changelog/unreleased_20/12077.rst new file mode 100644 index 0000000000..ac1c5a95e5 --- /dev/null +++ b/doc/build/changelog/unreleased_20/12077.rst @@ -0,0 +1,7 @@ +.. change:: + :tags: postgresql, usecase, asyncio + :tickets: 12077 + + Added an additional ``shield()`` call within the connection terminate + process of the asyncpg driver, to mitigate an issue where terminate would + be prevented from completing under the anyio concurrency library. diff --git a/lib/sqlalchemy/dialects/postgresql/asyncpg.py b/lib/sqlalchemy/dialects/postgresql/asyncpg.py index 523c47abcd..0cc1e99cca 100644 --- a/lib/sqlalchemy/dialects/postgresql/asyncpg.py +++ b/lib/sqlalchemy/dialects/postgresql/asyncpg.py @@ -904,7 +904,7 @@ class AsyncAdapt_asyncpg_connection(AdaptedConnection): try: # try to gracefully close; see #10717 # timeout added in asyncpg 0.14.0 December 2017 - self.await_(self._connection.close(timeout=2)) + self.await_(asyncio.shield(self._connection.close(timeout=2))) except ( asyncio.TimeoutError, asyncio.CancelledError, -- 2.47.3