Skip to content

Commit 56ab5fd

Browse files
committed
Protect from accidental garbage collection of asyncio tasks
1 parent d89843e commit 56ab5fd

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

sqlalchemy_bind_manager/_session_handler.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,10 @@ def commit(self, session: Session) -> None:
7373
raise
7474

7575

76+
# Reference: https://docs.astral.sh/ruff/rules/asyncio-dangling-task/
77+
_background_asyncio_tasks = set()
78+
79+
7680
class AsyncSessionHandler:
7781
scoped_session: async_scoped_session
7882

@@ -91,7 +95,14 @@ def __del__(self):
9195
try:
9296
loop = asyncio.get_event_loop()
9397
if loop.is_running():
94-
loop.create_task(self.scoped_session.remove())
98+
task = loop.create_task(self.scoped_session.remove())
99+
# Add task to the set. This creates a strong reference.
100+
_background_asyncio_tasks.add(task)
101+
102+
# To prevent keeping references to finished tasks forever,
103+
# make each task remove its own reference from the set after
104+
# completion:
105+
task.add_done_callback(_background_asyncio_tasks.discard)
95106
else:
96107
loop.run_until_complete(self.scoped_session.remove())
97108
except RuntimeError:

0 commit comments

Comments
 (0)