From fa6a9ca7dec39cba4801ce3dfec5b19e04c8b0ce Mon Sep 17 00:00:00 2001 From: Dmitry Anfimov Date: Thu, 26 Nov 2026 00:21:08 +0100 Subject: [PATCH] fix: keep and cancel delayed NOTIFY tasks in the asyncpg and psqlpy brokers The tasks were created without a reference, so they could be garbage collected while waiting, and shutdown() did not cancel them. A psqlpy producer that shut down its broker and kept running logged 'Task exception was never retrieved ... Pool has been closed' for every pending delayed message. Both brokers now track these tasks and cancel them on shutdown, like the psycopg and aiopg brokers. --- src/taskiq_pg/asyncpg/broker.py | 12 ++++-- src/taskiq_pg/psqlpy/broker.py | 12 ++++-- .../integration/test_shutdown_cancellation.py | 39 +++++++++++++++++++ 3 files changed, 57 insertions(+), 6 deletions(-) diff --git a/src/taskiq_pg/asyncpg/broker.py b/src/taskiq_pg/asyncpg/broker.py index e5f38d8..8a4aff8 100644 --- a/src/taskiq_pg/asyncpg/broker.py +++ b/src/taskiq_pg/asyncpg/broker.py @@ -44,6 +44,7 @@ class AsyncpgBroker(BasePostgresBroker): _owns_read_conn: bool _listener_task: asyncio.Task[None] | None = None _listener_disconnected: asyncio.Event + _notify_tasks: set[asyncio.Task[None]] @tp.overload def __init__( @@ -190,6 +191,8 @@ def __init__( # noqa: PLR0913 self._read_conn = read_connection self._owns_read_conn = False + self._notify_tasks = set() + async def startup(self) -> None: """Initialize the broker.""" await super().startup() @@ -231,6 +234,8 @@ async def shutdown(self) -> None: if self._listener_task is not None: await cancel_and_wait(self._listener_task) self._listener_task = None + for task in list(self._notify_tasks): + await cancel_and_wait(task) await super().shutdown() if self._read_conn is not None: self._read_conn.remove_termination_listener(self._connection_terminated) @@ -381,9 +386,10 @@ async def kick(self, message: BrokerMessage) -> None: ) if delay_seconds is not None: - _ = asyncio.create_task( # noqa: RUF006 - self._schedule_notification(message_inserted_id, delay_seconds), - ) + # Keep a reference, so the task is not garbage collected, and cancel it on shutdown. + task = asyncio.create_task(self._schedule_notification(message_inserted_id, delay_seconds)) + self._notify_tasks.add(task) + task.add_done_callback(self._notify_tasks.discard) else: # Send a NOTIFY with the message ID as payload _ = await conn.execute( diff --git a/src/taskiq_pg/psqlpy/broker.py b/src/taskiq_pg/psqlpy/broker.py index 94ec891..01e4b65 100644 --- a/src/taskiq_pg/psqlpy/broker.py +++ b/src/taskiq_pg/psqlpy/broker.py @@ -62,6 +62,7 @@ class PSQLPyBroker(BasePostgresBroker): _listener_task: asyncio.Task[None] | None = None _queue: asyncio.Queue _owns_write_pool: bool + _notify_tasks: set[asyncio.Task[None]] def __init__( # noqa: PLR0913 self, @@ -119,6 +120,8 @@ def __init__( # noqa: PLR0913 self._write_pool = write_pool self._owns_write_pool = False + self._notify_tasks = set() + async def startup(self) -> None: """Initialize the broker.""" await super().startup() @@ -165,6 +168,8 @@ async def shutdown(self) -> None: if self._listener_task is not None: await cancel_and_wait(self._listener_task) self._listener_task = None + for task in list(self._notify_tasks): + await cancel_and_wait(task) # startup() may have failed before creating these listener = getattr(self, "_listener", None) if listener is not None: @@ -300,9 +305,10 @@ async def kick(self, message: BrokerMessage) -> None: ) if delay_seconds is not None: - asyncio.create_task( # noqa: RUF006 - self._schedule_notification(message_inserted_id, delay_seconds), - ) + # Keep a reference, so the task is not garbage collected, and cancel it on shutdown. + task = asyncio.create_task(self._schedule_notification(message_inserted_id, delay_seconds)) + self._notify_tasks.add(task) + task.add_done_callback(self._notify_tasks.discard) else: # Send NOTIFY with message ID as payload _ = await conn.execute( diff --git a/tests/integration/test_shutdown_cancellation.py b/tests/integration/test_shutdown_cancellation.py index 705f72e..0d72230 100644 --- a/tests/integration/test_shutdown_cancellation.py +++ b/tests/integration/test_shutdown_cancellation.py @@ -1,10 +1,15 @@ import asyncio +import gc +import typing as tp +import uuid import pytest +from taskiq import BrokerMessage from taskiq_pg.aiopg import AiopgBroker from taskiq_pg.asyncpg import AsyncpgBroker from taskiq_pg.psqlpy import PSQLPyBroker +from taskiq_pg.psycopg import PsycopgBroker async def slow_to_cancel() -> None: @@ -47,3 +52,37 @@ async def test_when_shutdown_is_cancelled__then_cancellation_is_propagated( assert shutdown.cancelled(), "shutdown() must not swallow its own cancellation" finally: await broker.shutdown() + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", [AsyncpgBroker, PsycopgBroker, PSQLPyBroker, AiopgBroker]) +async def test_when_broker_shuts_down_before_a_delayed_notification__then_the_notification_is_cancelled( + pg_dsn: str, + broker_class: type[AiopgBroker | AsyncpgBroker | PsycopgBroker | PSQLPyBroker], +) -> None: + # given + suffix = uuid.uuid4().hex[:12] + broker = broker_class(dsn=pg_dsn, table_name=f"delayed_{suffix}", channel_name=f"delayed_{suffix}") + await broker.startup() + errors: list[dict[str, tp.Any]] = [] + loop = asyncio.get_running_loop() + previous_handler = loop.get_exception_handler() + loop.set_exception_handler(lambda _loop, context: errors.append(context)) + try: + message = BrokerMessage( + task_id=uuid.uuid4().hex, + task_name="example:delayed", + message=b"{}", + labels={"delay": 1}, + ) + await broker.kick(message) + + # when: the producer shuts down and keeps running past the delay + await asyncio.wait_for(broker.shutdown(), timeout=5) + await asyncio.sleep(1.5) + gc.collect() + + # then: the delayed NOTIFY did not run against the closed pool + assert [context.get("message") for context in errors] == [] + finally: + loop.set_exception_handler(previous_handler)