From 8d9e61af296e9fc1c1ad3dfe8cc8f9514dbe5222 Mon Sep 17 00:00:00 2001 From: Dmitry Anfimov Date: Wed, 25 Nov 2026 19:39:16 +0100 Subject: [PATCH 01/10] feat(asyncpg): poll for pending messages whose NOTIFY was missed A NOTIFY nobody is listening to is lost, and its message stayed pending forever: messages kicked while no worker was running (e.g. during a deploy) or while a worker was reconnecting, and delayed messages whose producer exited before sending the delayed NOTIFY. Add poll_interval (default 5 s) to the brokers. The asyncpg worker claims the oldest ready pending message (FOR UPDATE SKIP LOCKED, so workers never claim the same row) right after it starts listening, after reconnecting and every poll_interval, draining a backlog without waiting between messages. A delayed message is ready once created_at + delay has passed. NOTIFY stays the fast path. A partial index on pending messages is created on startup. --- src/taskiq_pg/_internal/broker.py | 11 ++ src/taskiq_pg/aiopg/broker.py | 7 + src/taskiq_pg/asyncpg/broker.py | 92 +++++++--- src/taskiq_pg/asyncpg/queries.py | 15 ++ src/taskiq_pg/psqlpy/broker.py | 3 + src/taskiq_pg/psycopg/broker.py | 7 + tests/integration/test_asyncpg_reconnect.py | 6 +- tests/integration/test_polling.py | 194 ++++++++++++++++++++ tests/unit/test_listen_keepalive_params.py | 19 ++ 9 files changed, 326 insertions(+), 28 deletions(-) create mode 100644 tests/integration/test_polling.py diff --git a/src/taskiq_pg/_internal/broker.py b/src/taskiq_pg/_internal/broker.py index 5377f2e..88c060a 100644 --- a/src/taskiq_pg/_internal/broker.py +++ b/src/taskiq_pg/_internal/broker.py @@ -29,6 +29,7 @@ def __init__( # noqa: PLR0913 *, listen_keepalive_interval: float | None = 30.0, listen_keepalive_timeout: float = 5.0, + poll_interval: float = 5.0, ) -> None: """ Construct a new broker. @@ -47,6 +48,9 @@ def __init__( # noqa: PLR0913 and detects a connection that hangs without being closed. None disables the check. listen_keepalive_timeout: How long, in seconds, to wait for the answer before treating the LISTEN connection as lost and reconnecting. + poll_interval: How often, in seconds, a listening worker looks for pending messages whose + NOTIFY it missed (sent while it was not listening or reconnecting), including delayed + messages whose delay has elapsed. It also polls right after start and after reconnecting. """ if listen_keepalive_interval is not None and listen_keepalive_interval <= 0: msg = "listen_keepalive_interval must be positive or None" @@ -54,6 +58,9 @@ def __init__( # noqa: PLR0913 if listen_keepalive_timeout <= 0: msg = "listen_keepalive_timeout must be positive" raise ValueError(msg) + if poll_interval <= 0: + msg = "poll_interval must be positive" + raise ValueError(msg) super().__init__( result_backend=result_backend, task_id_generator=task_id_generator, @@ -66,8 +73,12 @@ def __init__( # noqa: PLR0913 self.max_retry_attempts: int = max_retry_attempts self.listen_keepalive_interval: float | None = listen_keepalive_interval self.listen_keepalive_timeout: float = listen_keepalive_timeout + self.poll_interval: float = poll_interval self._queue: asyncio.Queue[str] | None = None LISTEN_KEEPALIVE_QUERY = "SELECT 1 /* taskiq-pg LISTEN keepalive */" """Query used to check a LISTEN connection; the comment makes it recognizable in pg_stat_activity.""" + +POLL_NOW = "" +"""Queue item that asks a listening worker to poll for pending messages right away (never a message id).""" diff --git a/src/taskiq_pg/aiopg/broker.py b/src/taskiq_pg/aiopg/broker.py index 0026425..5a12289 100644 --- a/src/taskiq_pg/aiopg/broker.py +++ b/src/taskiq_pg/aiopg/broker.py @@ -49,6 +49,7 @@ def __init__( read_connection: None = ..., listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., + poll_interval: float = ..., ) -> None: ... @tp.overload @@ -67,6 +68,7 @@ def __init__( read_connection: None = ..., listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., + poll_interval: float = ..., ) -> None: ... @tp.overload @@ -85,6 +87,7 @@ def __init__( read_connection: aiopg.Connection, listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., + poll_interval: float = ..., ) -> None: ... @tp.overload @@ -103,6 +106,7 @@ def __init__( read_connection: aiopg.Connection, listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., + poll_interval: float = ..., ) -> None: ... def __init__( # noqa: PLR0913 @@ -120,6 +124,7 @@ def __init__( # noqa: PLR0913 read_connection: aiopg.Connection | None = None, listen_keepalive_interval: float | None = 30.0, listen_keepalive_timeout: float = 5.0, + poll_interval: float = 5.0, ) -> None: """ Construct a new AiopgBroker. @@ -139,6 +144,7 @@ def __init__( # noqa: PLR0913 listen_keepalive_interval: How often, in seconds, to check the broker-owned LISTEN connection with a query; None disables the check. listen_keepalive_timeout: How long, in seconds, to wait for the check before reconnecting. + poll_interval: How often, in seconds, to look for pending messages whose NOTIFY was missed. """ super().__init__( dsn=dsn, @@ -151,6 +157,7 @@ def __init__( # noqa: PLR0913 write_kwargs=write_kwargs, listen_keepalive_interval=listen_keepalive_interval, listen_keepalive_timeout=listen_keepalive_timeout, + poll_interval=poll_interval, ) self._owns_write_pool = True diff --git a/src/taskiq_pg/asyncpg/broker.py b/src/taskiq_pg/asyncpg/broker.py index 39b3210..6e8cd75 100644 --- a/src/taskiq_pg/asyncpg/broker.py +++ b/src/taskiq_pg/asyncpg/broker.py @@ -7,12 +7,14 @@ import asyncpg from taskiq import AckableMessage, AsyncResultBackend, BrokerMessage -from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, BasePostgresBroker +from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, POLL_NOW, BasePostgresBroker from taskiq_pg._internal.retry import retry_delays from taskiq_pg._internal.tasks import cancel_and_wait from taskiq_pg.asyncpg.queries import ( CLAIM_MESSAGE_QUERY, + CLAIM_NEXT_READY_MESSAGE_QUERY, CREATE_MESSAGE_TABLE_QUERY, + CREATE_PENDING_INDEX_QUERY, DELETE_MESSAGE_QUERY, INSERT_MESSAGE_QUERY, ) @@ -49,6 +51,7 @@ def __init__( read_connection: None = ..., listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., + poll_interval: float = ..., ) -> None: ... @tp.overload @@ -67,6 +70,7 @@ def __init__( read_connection: None = ..., listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., + poll_interval: float = ..., ) -> None: ... @tp.overload @@ -85,6 +89,7 @@ def __init__( read_connection: asyncpg.Connection, listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., + poll_interval: float = ..., ) -> None: ... @tp.overload @@ -103,6 +108,7 @@ def __init__( read_connection: asyncpg.Connection, listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., + poll_interval: float = ..., ) -> None: ... def __init__( # noqa: PLR0913 @@ -120,6 +126,7 @@ def __init__( # noqa: PLR0913 read_connection: asyncpg.Connection | None = None, listen_keepalive_interval: float | None = 30.0, listen_keepalive_timeout: float = 5.0, + poll_interval: float = 5.0, ) -> None: """ Construct a new AsyncpgBroker. @@ -139,6 +146,7 @@ def __init__( # noqa: PLR0913 listen_keepalive_interval: How often, in seconds, to check the broker-owned LISTEN connection with a query; None disables the check. listen_keepalive_timeout: How long, in seconds, to wait for the check before reconnecting. + poll_interval: How often, in seconds, to look for pending messages whose NOTIFY was missed. """ super().__init__( dsn=dsn, @@ -151,6 +159,7 @@ def __init__( # noqa: PLR0913 write_kwargs=write_kwargs, listen_keepalive_interval=listen_keepalive_interval, listen_keepalive_timeout=listen_keepalive_timeout, + poll_interval=poll_interval, ) self._owns_write_pool = True @@ -172,6 +181,9 @@ async def startup(self) -> None: self._write_pool = await asyncpg.create_pool(self.dsn, **self.write_kwargs) async with self._write_pool.acquire() as conn: await conn.execute(CREATE_MESSAGE_TABLE_QUERY.format(self.table_name)) + await conn.execute( + CREATE_PENDING_INDEX_QUERY.format(index=f"{self.table_name}_pending_idx", table=self.table_name), + ) await self._connect_listener() self._listener_task = asyncio.create_task(self._restore_listener()) @@ -241,6 +253,8 @@ async def _restore_listener(self) -> None: await asyncio.sleep(delay) else: logger.info("LISTEN connection restored on channel %s", self.channel_name) + if self._queue is not None: # notifications sent while reconnecting were missed + self._queue.put_nowait(POLL_NOW) break async def _wait_for_disconnection(self) -> None: @@ -359,35 +373,59 @@ async def listen(self) -> AsyncGenerator[AckableMessage, None]: msg = "Startup did not initialize the queue." raise ValueError(msg) + queue = self._queue + loop = asyncio.get_running_loop() + next_poll = loop.time() # poll right away: messages may have been kicked while nobody listened while True: try: - payload = await self._queue.get() - message_id = int(payload) - async with self._write_pool.acquire() as conn: - claimed = await conn.fetchrow( - CLAIM_MESSAGE_QUERY.format(self.table_name), - message_id, - ) - if claimed is None: + if loop.time() >= next_poll: + next_poll = loop.time() + self.poll_interval + while (claimed := await self._claim_next_ready()) is not None: + yield self._ackable(claimed) + continue + try: + payload = await asyncio.wait_for(queue.get(), next_poll - loop.time()) + except TimeoutError: + continue + if payload == POLL_NOW: + next_poll = loop.time() continue - message_str = claimed["message"] - if not isinstance(message_str, str): - msg = "message is not a string" - raise TypeError(msg) - message_data = message_str.encode() - - async def ack(*, _message_id: int = message_id) -> None: - if self._write_pool is None: - msg = "Call startup before starting listening." - raise ValueError(msg) - - async with self._write_pool.acquire() as conn: - _ = await conn.execute( - DELETE_MESSAGE_QUERY.format(self.table_name), - _message_id, - ) - - yield AckableMessage(data=message_data, ack=ack) + claimed = await self._claim(int(payload)) + if claimed is not None: + yield self._ackable(claimed) except Exception: logger.exception("Error processing message") continue + + async def _claim(self, message_id: int) -> asyncpg.Record | None: + """Claim a pending message by its id.""" + if self._write_pool is None: + msg = "Call startup before starting listening." + raise ValueError(msg) + async with self._write_pool.acquire() as conn: + return await conn.fetchrow(CLAIM_MESSAGE_QUERY.format(self.table_name), message_id) + + async def _claim_next_ready(self) -> asyncpg.Record | None: + """Claim the oldest pending message that is ready (its delay, if any, has elapsed).""" + if self._write_pool is None: + msg = "Call startup before starting listening." + raise ValueError(msg) + async with self._write_pool.acquire() as conn: + return await conn.fetchrow(CLAIM_NEXT_READY_MESSAGE_QUERY.format(table=self.table_name)) + + def _ackable(self, claimed: asyncpg.Record) -> AckableMessage: + """Wrap a claimed message; acknowledging it deletes the row.""" + message_str = claimed["message"] + if not isinstance(message_str, str): + msg = "message is not a string" + raise TypeError(msg) + message_id = int(claimed["id"]) + + async def ack() -> None: + if self._write_pool is None: + msg = "Call startup before starting listening." + raise ValueError(msg) + async with self._write_pool.acquire() as conn: + await conn.execute(DELETE_MESSAGE_QUERY.format(self.table_name), message_id) + + return AckableMessage(data=message_str.encode(), ack=ack) diff --git a/src/taskiq_pg/asyncpg/queries.py b/src/taskiq_pg/asyncpg/queries.py index a504d05..2eb8864 100644 --- a/src/taskiq_pg/asyncpg/queries.py +++ b/src/taskiq_pg/asyncpg/queries.py @@ -99,3 +99,18 @@ DELETE_SCHEDULE_QUERY = """ DELETE FROM {} WHERE id = $1; """ + +CREATE_PENDING_INDEX_QUERY = "CREATE INDEX IF NOT EXISTS {index} ON {table} (id) WHERE status = 'pending'" + +CLAIM_NEXT_READY_MESSAGE_QUERY = """ +UPDATE {table} SET status = 'processing' +WHERE id = ( + SELECT id FROM {table} + WHERE status = 'pending' + AND created_at + make_interval(secs => COALESCE((labels->>'delay')::double precision, 0)) <= now() + ORDER BY id + LIMIT 1 + FOR UPDATE SKIP LOCKED +) +RETURNING id, message +""" diff --git a/src/taskiq_pg/psqlpy/broker.py b/src/taskiq_pg/psqlpy/broker.py index eb8f200..c862b3d 100644 --- a/src/taskiq_pg/psqlpy/broker.py +++ b/src/taskiq_pg/psqlpy/broker.py @@ -62,6 +62,7 @@ def __init__( # noqa: PLR0913 write_pool: psqlpy.ConnectionPool | None = None, listen_keepalive_interval: float | None = 30.0, listen_keepalive_timeout: float = 5.0, + poll_interval: float = 5.0, ) -> None: """ Construct a new PSQLPyBroker. @@ -80,6 +81,7 @@ def __init__( # noqa: PLR0913 listen_keepalive_interval: How often, in seconds, to check the broker-owned LISTEN connection with a query; None disables the check. listen_keepalive_timeout: How long, in seconds, to wait for the check before reconnecting. + poll_interval: How often, in seconds, to look for pending messages whose NOTIFY was missed. """ super().__init__( dsn=dsn, @@ -91,6 +93,7 @@ def __init__( # noqa: PLR0913 write_kwargs=write_kwargs, listen_keepalive_interval=listen_keepalive_interval, listen_keepalive_timeout=listen_keepalive_timeout, + poll_interval=poll_interval, ) self._owns_write_pool = True diff --git a/src/taskiq_pg/psycopg/broker.py b/src/taskiq_pg/psycopg/broker.py index 8466b0f..045120c 100644 --- a/src/taskiq_pg/psycopg/broker.py +++ b/src/taskiq_pg/psycopg/broker.py @@ -58,6 +58,7 @@ def __init__( read_connection: None = ..., listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., + poll_interval: float = ..., ) -> None: ... @tp.overload @@ -76,6 +77,7 @@ def __init__( read_connection: None = ..., listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., + poll_interval: float = ..., ) -> None: ... @tp.overload @@ -94,6 +96,7 @@ def __init__( read_connection: AsyncConnection, listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., + poll_interval: float = ..., ) -> None: ... @tp.overload @@ -112,6 +115,7 @@ def __init__( read_connection: AsyncConnection, listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., + poll_interval: float = ..., ) -> None: ... def __init__( # noqa: PLR0913 @@ -129,6 +133,7 @@ def __init__( # noqa: PLR0913 read_connection: AsyncConnection | None = None, listen_keepalive_interval: float | None = 30.0, listen_keepalive_timeout: float = 5.0, + poll_interval: float = 5.0, ) -> None: """ Construct a new PsycopgBroker. @@ -148,6 +153,7 @@ def __init__( # noqa: PLR0913 listen_keepalive_interval: How often, in seconds, to check the broker-owned LISTEN connection with a query; None disables the check. listen_keepalive_timeout: How long, in seconds, to wait for the check before reconnecting. + poll_interval: How often, in seconds, to look for pending messages whose NOTIFY was missed. """ super().__init__( dsn=dsn, @@ -160,6 +166,7 @@ def __init__( # noqa: PLR0913 write_kwargs=write_kwargs, listen_keepalive_interval=listen_keepalive_interval, listen_keepalive_timeout=listen_keepalive_timeout, + poll_interval=poll_interval, ) self._owns_write_pool = True diff --git a/tests/integration/test_asyncpg_reconnect.py b/tests/integration/test_asyncpg_reconnect.py index 0428a04..ffdda37 100644 --- a/tests/integration/test_asyncpg_reconnect.py +++ b/tests/integration/test_asyncpg_reconnect.py @@ -7,6 +7,7 @@ import pytest from taskiq import BrokerMessage +from taskiq_pg._internal.broker import POLL_NOW from taskiq_pg.asyncpg import AsyncpgBroker @@ -144,7 +145,10 @@ async def fail_once( queue = broker._queue # noqa: SLF001 assert queue is not None await connection.execute(f"NOTIFY {broker.channel_name}, '42'") - assert await asyncio.wait_for(queue.get(), timeout=5) == "42" + payload = await asyncio.wait_for(queue.get(), timeout=5) + while payload == POLL_NOW: # reconnecting also asks the worker to poll the table + payload = await asyncio.wait_for(queue.get(), timeout=5) + assert payload == "42" assert len(failed_connections) == 1 assert failed_connections[0].is_closed() finally: diff --git a/tests/integration/test_polling.py b/tests/integration/test_polling.py new file mode 100644 index 0000000..61d8789 --- /dev/null +++ b/tests/integration/test_polling.py @@ -0,0 +1,194 @@ +import asyncio +import json +import typing as tp +import uuid + +import asyncpg +import pytest +from taskiq import AckableMessage, BrokerMessage + +from taskiq_pg.asyncpg import AsyncpgBroker + + +Broker: tp.TypeAlias = AsyncpgBroker +BROKERS: list[tp.Any] = [AsyncpgBroker] + + +def unique_names() -> dict[str, str]: + suffix = uuid.uuid4().hex[:12] + return {"table_name": f"poll_{suffix}", "channel_name": f"poll_{suffix}"} + + +async def insert_pending(connection: asyncpg.Connection, table: str, data: str, labels: dict[str, tp.Any]) -> int: + """Insert a pending message without sending a NOTIFY, like a kick whose notification was missed.""" + return tp.cast( + "int", + await connection.fetchval( + f"INSERT INTO {table} (task_id, task_name, message, labels) VALUES ($1, $2, $3, $4) RETURNING id", # noqa: S608 + uuid.uuid4().hex, + "example:polled", + data, + json.dumps(labels), + ), + ) + + +async def take(listener: tp.AsyncIterator[AckableMessage], count: int, timeout: float) -> list[bytes]: + """Read `count` messages from a listener within `timeout` seconds.""" + + async def read() -> list[bytes]: + return [(await anext(listener)).data for _ in range(count)] + + return await asyncio.wait_for(read(), timeout) + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", BROKERS) +async def test_when_message_was_inserted_without_notify__then_worker_claims_it_by_polling( + pg_dsn: str, + connection: asyncpg.Connection, + broker_class: type[Broker], +) -> None: + # given + names = unique_names() + broker = broker_class(dsn=pg_dsn, poll_interval=0.2, **names) + await broker.startup() + listener = broker.listen() + try: + # when + await insert_pending(connection, names["table_name"], '{"polled":true}', {}) + + # then + assert await take(listener, 1, timeout=3) == [b'{"polled":true}'] + finally: + await listener.aclose() + await broker.shutdown() + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", BROKERS) +async def test_when_messages_were_kicked_before_worker_started__then_worker_processes_them( + pg_dsn: str, + broker_class: type[Broker], +) -> None: + # given + names = unique_names() + producer = broker_class(dsn=pg_dsn, **names) + await producer.startup() + expected = {f'{{"n":{n}}}'.encode() for n in range(5)} + for data in expected: + await producer.kick( + BrokerMessage(task_id=uuid.uuid4().hex, task_name="example:early", message=data, labels={}), + ) + worker = broker_class(dsn=pg_dsn, **names) + + # when + await worker.startup() + listener = worker.listen() + try: + received = await take(listener, len(expected), timeout=3) + + # then + assert set(received) == expected + finally: + await listener.aclose() + await worker.shutdown() + await producer.shutdown() + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", BROKERS) +async def test_when_delayed_message_was_not_notified__then_it_is_claimed_after_its_delay( + pg_dsn: str, + connection: asyncpg.Connection, + broker_class: type[Broker], +) -> None: + # given + names = unique_names() + broker = broker_class(dsn=pg_dsn, poll_interval=0.2, **names) + await broker.startup() + listener = broker.listen() + pending: asyncio.Task[AckableMessage] = asyncio.create_task(anext(listener)) # type: ignore[arg-type] + try: + # when + await insert_pending(connection, names["table_name"], '{"delayed":true}', {"delay": 1}) + done, _ = await asyncio.wait({pending}, timeout=0.6) + + # then + assert not done, "A delayed message must not be claimed before its delay elapses" + done, _ = await asyncio.wait({pending}, timeout=3) + assert pending in done + assert pending.result().data == b'{"delayed":true}' + finally: + pending.cancel() + await asyncio.gather(pending, return_exceptions=True) + await broker.shutdown() + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", BROKERS) +async def test_when_two_workers_poll__then_each_message_is_claimed_once( + pg_dsn: str, + connection: asyncpg.Connection, + broker_class: type[Broker], +) -> None: + # given + names = unique_names() + first = broker_class(dsn=pg_dsn, poll_interval=0.2, **names) + second = broker_class(dsn=pg_dsn, poll_interval=0.2, **names) + await first.startup() + await second.startup() + expected = [f'{{"n":{n}}}' for n in range(20)] + for data in expected: + await insert_pending(connection, names["table_name"], data, {}) + received: list[bytes] = [] + + async def consume(broker: Broker) -> None: + async for message in broker.listen(): + received.append(message.data) # noqa: PERF401 - the loop runs until cancelled + + # when + consumers = [asyncio.create_task(consume(first)), asyncio.create_task(consume(second))] + try: + + async def all_received() -> None: + while len(received) < len(expected): # noqa: ASYNC110 + await asyncio.sleep(0.05) + + await asyncio.wait_for(all_received(), timeout=5) + await asyncio.sleep(0.5) # give a duplicate the chance to show up + + # then + assert sorted(received) == sorted(data.encode() for data in expected) + finally: + for consumer in consumers: + consumer.cancel() + await asyncio.gather(*consumers, return_exceptions=True) + await first.shutdown() + await second.shutdown() + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", BROKERS) +async def test_when_broker_starts__then_pending_index_is_created( + pg_dsn: str, + connection: asyncpg.Connection, + broker_class: type[Broker], +) -> None: + # given + names = unique_names() + broker = broker_class(dsn=pg_dsn, **names) + + # when + await broker.startup() + try: + definition = await connection.fetchval( + "SELECT indexdef FROM pg_indexes WHERE indexname = $1", + f"{names['table_name']}_pending_idx", + ) + + # then + assert definition is not None + assert "WHERE (status = 'pending'::text)" in definition + finally: + await broker.shutdown() diff --git a/tests/unit/test_listen_keepalive_params.py b/tests/unit/test_listen_keepalive_params.py index 99284cb..11f7c76 100644 --- a/tests/unit/test_listen_keepalive_params.py +++ b/tests/unit/test_listen_keepalive_params.py @@ -50,3 +50,22 @@ def test_when_keepalive_settings_are_invalid__then_error_is_raised( # when / then with pytest.raises(ValueError, match=match): broker_class(**kwargs) + + +@pytest.mark.unit +@pytest.mark.parametrize("broker_class", BROKERS) +def test_when_broker_is_created__then_poll_interval_defaults_to_five_seconds(broker_class: tp.Any) -> None: + # when + broker = broker_class() + + # then + assert broker.poll_interval == 5.0 + + +@pytest.mark.unit +@pytest.mark.parametrize("broker_class", BROKERS) +@pytest.mark.parametrize("poll_interval", [0, -1]) +def test_when_poll_interval_is_not_positive__then_error_is_raised(broker_class: tp.Any, poll_interval: float) -> None: + # when / then + with pytest.raises(ValueError, match="poll_interval"): + broker_class(poll_interval=poll_interval) From 5927f5461ee5dd502561443735990b42561d8cd0 Mon Sep 17 00:00:00 2001 From: Dmitry Anfimov Date: Wed, 25 Nov 2026 19:41:34 +0100 Subject: [PATCH 02/10] feat(psycopg): poll for pending messages whose NOTIFY was missed The notification loop now also yields a poll marker: right after start and after every reconnect, then every poll_interval. The connection is read in slices up to the next poll or keepalive query (notifies(timeout=...)), and listen() drains every ready pending message when the marker arrives. A database error while polling is logged and retried on the next poll instead of ending listen(). --- src/taskiq_pg/psycopg/broker.py | 115 ++++++++++++++++++++---------- src/taskiq_pg/psycopg/queries.py | 15 ++++ tests/integration/test_polling.py | 5 +- 3 files changed, 94 insertions(+), 41 deletions(-) diff --git a/src/taskiq_pg/psycopg/broker.py b/src/taskiq_pg/psycopg/broker.py index 045120c..315b791 100644 --- a/src/taskiq_pg/psycopg/broker.py +++ b/src/taskiq_pg/psycopg/broker.py @@ -10,11 +10,13 @@ from psycopg_pool import AsyncConnectionPool from taskiq import AckableMessage, AsyncResultBackend, BrokerMessage -from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, BasePostgresBroker +from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, POLL_NOW, BasePostgresBroker from taskiq_pg._internal.retry import retry_delays from taskiq_pg.psycopg.queries import ( CLAIM_MESSAGE_QUERY, + CLAIM_NEXT_READY_MESSAGE_QUERY, CREATE_MESSAGE_TABLE_QUERY, + CREATE_PENDING_INDEX_QUERY, DELETE_MESSAGE_QUERY, INSERT_MESSAGE_QUERY, ) @@ -196,6 +198,12 @@ async def startup(self) -> None: async with self._write_pool.connection() as connection, connection.cursor() as cursor: await cursor.execute(sql.SQL(CREATE_MESSAGE_TABLE_QUERY).format(sql.Identifier(self.table_name))) + await cursor.execute( + sql.SQL(CREATE_PENDING_INDEX_QUERY).format( + index=sql.Identifier(f"{self.table_name}_pending_idx"), + table=sql.Identifier(self.table_name), + ), + ) if self._owns_read_conn: await self._connect_listener() @@ -325,23 +333,30 @@ async def _schedule_notification(self, message_id: int, delay_seconds: int) -> N async def _notifications(self) -> AsyncGenerator[str, None]: """ - Yield notification payloads from the current LISTEN connection. + Yield notification payloads from the current LISTEN connection, and POLL_NOW when it is time to poll. - A broker-owned connection is read in slices of `listen_keepalive_interval` seconds with a - keepalive query in between; a query that does not answer in time raises OperationalError. + POLL_NOW comes first, so the table is polled right after start and after every reconnect. The + connection is read in slices up to the next poll and, for a broker-owned connection, up to the + next keepalive query; a keepalive query that does not answer in time raises OperationalError. """ - interval = self.listen_keepalive_interval - if interval is None or not self._owns_read_conn: - async for notify in self._notifies_iter: - yield notify.payload - return + keepalive = self.listen_keepalive_interval if self._owns_read_conn else None + loop = asyncio.get_running_loop() + next_poll = loop.time() + next_keepalive = None if keepalive is None else loop.time() + keepalive while not self._is_closing(): - self._notifies_iter = self._read_conn.notifies(timeout=interval) + now = loop.time() + if now >= next_poll: + next_poll = now + self.poll_interval + yield POLL_NOW + continue + if keepalive is not None and next_keepalive is not None and now >= next_keepalive: + await self._check_listener() + next_keepalive = loop.time() + keepalive + continue + deadline = next_poll if next_keepalive is None else min(next_poll, next_keepalive) + self._notifies_iter = self._read_conn.notifies(timeout=deadline - now) async for notify in self._notifies_iter: yield notify.payload - if self._is_closing(): - return - await self._check_listener() async def _check_listener(self) -> None: """ @@ -393,30 +408,52 @@ async def listen(self) -> AsyncGenerator[AckableMessage, None]: :yields: AckableMessage instances. """ - async for message_id_str in self._listen_context(): - message_id = int(message_id_str) # payload is the message id - try: - async with self._write_pool.connection() as connection, connection.cursor() as cursor: - await cursor.execute( - sql.SQL(CLAIM_MESSAGE_QUERY).format(sql.Identifier(self.table_name)), - [message_id], - ) - claimed_message = await cursor.fetchone() - if claimed_message is None: - continue - except psycopg.OperationalError: # message was claimed by another worker + async for payload in self._listen_context(): + if payload == POLL_NOW: + while (claimed := await self._claim_next_ready()) is not None: + yield self._ackable(claimed) continue - message_str = claimed_message[3] - if not isinstance(message_str, str): - msg = "Message is not a string" - raise TypeError(msg) - message_data = message_str.encode() - - async def ack(*, _message_id: int = message_id) -> None: - async with self._write_pool.connection() as connection, connection.cursor() as cursor: - await cursor.execute( - sql.SQL(DELETE_MESSAGE_QUERY).format(sql.Identifier(self.table_name)), - [_message_id], - ) - - yield AckableMessage(data=message_data, ack=ack) + claimed = await self._claim(int(payload)) # payload is the message id + if claimed is not None: + yield self._ackable(claimed) + + async def _claim(self, message_id: int) -> tuple[tp.Any, ...] | None: + """Claim a pending message by its id.""" + try: + async with self._write_pool.connection() as connection, connection.cursor() as cursor: + await cursor.execute( + sql.SQL(CLAIM_MESSAGE_QUERY).format(sql.Identifier(self.table_name)), + [message_id], + ) + return await cursor.fetchone() + except psycopg.OperationalError: # message was claimed by another worker + return None + + async def _claim_next_ready(self) -> tuple[tp.Any, ...] | None: + """Claim the oldest pending message that is ready (its delay, if any, has elapsed).""" + try: + async with self._write_pool.connection() as connection, connection.cursor() as cursor: + await cursor.execute( + sql.SQL(CLAIM_NEXT_READY_MESSAGE_QUERY).format(table=sql.Identifier(self.table_name)), + ) + return await cursor.fetchone() + except psycopg.OperationalError: + logger.warning("Polling for pending messages failed; will retry", exc_info=True) + return None + + def _ackable(self, claimed: tuple[tp.Any, ...]) -> AckableMessage: + """Wrap a claimed message; acknowledging it deletes the row.""" + message_id = int(claimed[0]) + message_str = claimed[3] + if not isinstance(message_str, str): + msg = "Message is not a string" + raise TypeError(msg) + + async def ack() -> None: + async with self._write_pool.connection() as connection, connection.cursor() as cursor: + await cursor.execute( + sql.SQL(DELETE_MESSAGE_QUERY).format(sql.Identifier(self.table_name)), + [message_id], + ) + + return AckableMessage(data=message_str.encode(), ack=ack) diff --git a/src/taskiq_pg/psycopg/queries.py b/src/taskiq_pg/psycopg/queries.py index b7e1b46..859ea5b 100644 --- a/src/taskiq_pg/psycopg/queries.py +++ b/src/taskiq_pg/psycopg/queries.py @@ -99,3 +99,18 @@ DELETE_SCHEDULE_QUERY = """ DELETE FROM {} WHERE id = %s; """ + +CREATE_PENDING_INDEX_QUERY = "CREATE INDEX IF NOT EXISTS {index} ON {table} (id) WHERE status = 'pending'" + +CLAIM_NEXT_READY_MESSAGE_QUERY = """ +UPDATE {table} SET status = 'processing' +WHERE id = ( + SELECT id FROM {table} + WHERE status = 'pending' + AND created_at + make_interval(secs => COALESCE((labels->>'delay')::double precision, 0)) <= now() + ORDER BY id + LIMIT 1 + FOR UPDATE SKIP LOCKED +) +RETURNING * +""" diff --git a/tests/integration/test_polling.py b/tests/integration/test_polling.py index 61d8789..44c6be3 100644 --- a/tests/integration/test_polling.py +++ b/tests/integration/test_polling.py @@ -8,10 +8,11 @@ from taskiq import AckableMessage, BrokerMessage from taskiq_pg.asyncpg import AsyncpgBroker +from taskiq_pg.psycopg import PsycopgBroker -Broker: tp.TypeAlias = AsyncpgBroker -BROKERS: list[tp.Any] = [AsyncpgBroker] +Broker: tp.TypeAlias = AsyncpgBroker | PsycopgBroker +BROKERS: list[tp.Any] = [AsyncpgBroker, PsycopgBroker] def unique_names() -> dict[str, str]: From 8792d16d432a41628ff6e8218ea8d4ded0ea3d0e Mon Sep 17 00:00:00 2001 From: Dmitry Anfimov Date: Wed, 25 Nov 2026 19:43:35 +0100 Subject: [PATCH 03/10] feat(psqlpy): poll for pending messages whose NOTIFY was missed Same as for asyncpg: the worker claims ready pending messages right after it starts listening, after the listener is restored and every poll_interval; a partial index on pending messages is created on startup. --- src/taskiq_pg/psqlpy/broker.py | 71 +++++++++++++++++++++---------- src/taskiq_pg/psqlpy/queries.py | 15 +++++++ tests/integration/test_polling.py | 5 ++- 3 files changed, 66 insertions(+), 25 deletions(-) diff --git a/src/taskiq_pg/psqlpy/broker.py b/src/taskiq_pg/psqlpy/broker.py index c862b3d..9fe9d28 100644 --- a/src/taskiq_pg/psqlpy/broker.py +++ b/src/taskiq_pg/psqlpy/broker.py @@ -11,12 +11,14 @@ from psqlpy.extra_types import JSONB from taskiq import AckableMessage, AsyncResultBackend, BrokerMessage -from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, BasePostgresBroker +from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, POLL_NOW, BasePostgresBroker from taskiq_pg._internal.retry import retry_delays from taskiq_pg._internal.tasks import cancel_and_wait, run_until_first_done from taskiq_pg.psqlpy.queries import ( CLAIM_MESSAGE_QUERY, + CLAIM_NEXT_READY_MESSAGE_QUERY, CREATE_MESSAGE_TABLE_QUERY, + CREATE_PENDING_INDEX_QUERY, DELETE_MESSAGE_QUERY, INSERT_MESSAGE_QUERY, ) @@ -114,6 +116,9 @@ async def startup(self) -> None: # create messages table if it doesn't exist async with self._write_pool.acquire() as conn: await conn.execute(CREATE_MESSAGE_TABLE_QUERY.format(self.table_name)) + await conn.execute( + CREATE_PENDING_INDEX_QUERY.format(index=f"{self.table_name}_pending_idx", table=self.table_name), + ) self._queue = asyncio.Queue() @@ -173,6 +178,7 @@ async def _consume_notifications(self) -> None: with suppress(Exception): await self._listener.shutdown() self._listener = await self._restore_listener() + self._queue.put_nowait(POLL_NOW) # notifications sent while reconnecting were missed async def _move_notifications(self, listener: psqlpy.Listener) -> None: """Move notifications from the listener into the queue until it stops or its connection is lost.""" @@ -281,32 +287,51 @@ async def listen(self) -> AsyncGenerator[AckableMessage, None]: :yields: AckableMessage instances. """ + loop = asyncio.get_running_loop() + next_poll = loop.time() # poll right away: messages may have been kicked while nobody listened while True: try: - payload = await self._queue.get() - message_id = int(payload) # payload is the message id + if loop.time() >= next_poll: + next_poll = loop.time() + self.poll_interval + while (claimed := await self._claim_next_ready()) is not None: + yield self._ackable(claimed) + continue try: - async with self._write_pool.acquire() as conn: - claimed_message = await conn.fetch_row( - CLAIM_MESSAGE_QUERY.format(self.table_name), - [message_id], - ) - except ConnectionExecuteError: # message was claimed by another worker + payload = await asyncio.wait_for(self._queue.get(), next_poll - loop.time()) + except TimeoutError: continue - message_row_result = tp.cast( - "MessageRow", - tp.cast("object", claimed_message.as_class(MessageRow)), - ) - message_data = message_row_result.message.encode() - - async def ack(*, _message_id: int = message_id) -> None: - async with self._write_pool.acquire() as conn: - _ = await conn.execute( - DELETE_MESSAGE_QUERY.format(self.table_name), - [_message_id], - ) - - yield AckableMessage(data=message_data, ack=ack) + if payload == POLL_NOW: + next_poll = loop.time() + continue + claimed = await self._claim(int(payload)) # payload is the message id + if claimed is not None: + yield self._ackable(claimed) except Exception: logger.exception("Error processing message") continue + + async def _claim(self, message_id: int) -> MessageRow | None: + """Claim a pending message by its id.""" + try: + async with self._write_pool.acquire() as conn: + claimed_message = await conn.fetch_row(CLAIM_MESSAGE_QUERY.format(self.table_name), [message_id]) + except ConnectionExecuteError: # message was claimed by another worker + return None + return tp.cast("MessageRow", tp.cast("object", claimed_message.as_class(MessageRow))) + + async def _claim_next_ready(self) -> MessageRow | None: + """Claim the oldest pending message that is ready (its delay, if any, has elapsed).""" + async with self._write_pool.acquire() as conn: + result = await conn.fetch(CLAIM_NEXT_READY_MESSAGE_QUERY.format(table=self.table_name)) + rows = tp.cast("list[MessageRow]", result.as_class(MessageRow)) + return rows[0] if rows else None + + def _ackable(self, claimed: MessageRow) -> AckableMessage: + """Wrap a claimed message; acknowledging it deletes the row.""" + message_id = claimed.id + + async def ack() -> None: + async with self._write_pool.acquire() as conn: + await conn.execute(DELETE_MESSAGE_QUERY.format(self.table_name), [message_id]) + + return AckableMessage(data=claimed.message.encode(), ack=ack) diff --git a/src/taskiq_pg/psqlpy/queries.py b/src/taskiq_pg/psqlpy/queries.py index 5214ebc..05b4dd3 100644 --- a/src/taskiq_pg/psqlpy/queries.py +++ b/src/taskiq_pg/psqlpy/queries.py @@ -99,3 +99,18 @@ DELETE_SCHEDULE_QUERY = """ DELETE FROM {} WHERE id = $1; """ + +CREATE_PENDING_INDEX_QUERY = "CREATE INDEX IF NOT EXISTS {index} ON {table} (id) WHERE status = 'pending'" + +CLAIM_NEXT_READY_MESSAGE_QUERY = """ +UPDATE {table} SET status = 'processing' +WHERE id = ( + SELECT id FROM {table} + WHERE status = 'pending' + AND created_at + make_interval(secs => COALESCE((labels->>'delay')::double precision, 0)) <= now() + ORDER BY id + LIMIT 1 + FOR UPDATE SKIP LOCKED +) +RETURNING * +""" diff --git a/tests/integration/test_polling.py b/tests/integration/test_polling.py index 44c6be3..012e878 100644 --- a/tests/integration/test_polling.py +++ b/tests/integration/test_polling.py @@ -8,11 +8,12 @@ from taskiq import AckableMessage, BrokerMessage from taskiq_pg.asyncpg import AsyncpgBroker +from taskiq_pg.psqlpy import PSQLPyBroker from taskiq_pg.psycopg import PsycopgBroker -Broker: tp.TypeAlias = AsyncpgBroker | PsycopgBroker -BROKERS: list[tp.Any] = [AsyncpgBroker, PsycopgBroker] +Broker: tp.TypeAlias = AsyncpgBroker | PsycopgBroker | PSQLPyBroker +BROKERS: list[tp.Any] = [AsyncpgBroker, PsycopgBroker, PSQLPyBroker] def unique_names() -> dict[str, str]: From b74f9130204012653c6b62d77bf924d63985343c Mon Sep 17 00:00:00 2001 From: Dmitry Anfimov Date: Wed, 25 Nov 2026 19:45:15 +0100 Subject: [PATCH 04/10] feat(aiopg): poll for pending messages whose NOTIFY was missed Same as for the other brokers: the worker claims ready pending messages right after it starts listening, after the LISTEN connection is restored and every poll_interval; a partial index on pending messages is created on startup. --- src/taskiq_pg/aiopg/broker.py | 74 ++++++++++++++++++++++--------- src/taskiq_pg/aiopg/queries.py | 15 +++++++ tests/integration/test_polling.py | 5 ++- 3 files changed, 71 insertions(+), 23 deletions(-) diff --git a/src/taskiq_pg/aiopg/broker.py b/src/taskiq_pg/aiopg/broker.py index 5a12289..910a883 100644 --- a/src/taskiq_pg/aiopg/broker.py +++ b/src/taskiq_pg/aiopg/broker.py @@ -7,12 +7,14 @@ import aiopg from taskiq import AckableMessage, AsyncResultBackend, BrokerMessage -from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, BasePostgresBroker +from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, POLL_NOW, BasePostgresBroker from taskiq_pg._internal.retry import retry_delays from taskiq_pg._internal.tasks import cancel_and_wait, run_until_first_done from taskiq_pg.aiopg.queries import ( CLAIM_MESSAGE_QUERY, + CLAIM_NEXT_READY_MESSAGE_QUERY, CREATE_MESSAGE_TABLE_QUERY, + CREATE_PENDING_INDEX_QUERY, DELETE_MESSAGE_QUERY, INSERT_MESSAGE_QUERY, ) @@ -180,6 +182,9 @@ async def startup(self) -> None: self._write_pool = await aiopg.create_pool(self.dsn, **self.write_kwargs) async with self._write_pool.acquire() as conn, conn.cursor() as cursor: await cursor.execute(CREATE_MESSAGE_TABLE_QUERY.format(self.table_name)) + await cursor.execute( + CREATE_PENDING_INDEX_QUERY.format(index=f"{self.table_name}_pending_idx", table=self.table_name), + ) if self._owns_read_conn: self._read_conn = await self._connect_listener() elif self._read_conn is not None: @@ -240,6 +245,8 @@ async def _consume_notifications(self) -> None: logger.warning("LISTEN connection lost on channel %s; reconnecting", self.channel_name, exc_info=True) await conn.close() self._read_conn = await self._restore_listener() + if self._queue is not None: # notifications sent while reconnecting were missed + self._queue.put_nowait(POLL_NOW) async def _move_notifications(self, conn: aiopg.Connection) -> None: """Move notifications into the queue until the connection is lost.""" @@ -337,29 +344,54 @@ async def listen(self) -> AsyncGenerator[AckableMessage, None]: msg = "Startup did not initialize the queue." raise ValueError(msg) + queue = self._queue + loop = asyncio.get_running_loop() + next_poll = loop.time() # poll right away: messages may have been kicked while nobody listened while True: try: - payload = await self._queue.get() - message_id = int(payload) - async with self._write_pool.acquire() as conn, conn.cursor() as cursor: - await cursor.execute(CLAIM_MESSAGE_QUERY.format(self.table_name), (message_id,)) - claimed = await cursor.fetchone() - if claimed is None: + if loop.time() >= next_poll: + next_poll = loop.time() + self.poll_interval + while ( + claimed := await self._claim(CLAIM_NEXT_READY_MESSAGE_QUERY.format(table=self.table_name)) + ) is not None: + yield self._ackable(claimed) + continue + try: + payload = await asyncio.wait_for(queue.get(), next_poll - loop.time()) + except TimeoutError: continue - message_str = claimed[1] - if not isinstance(message_str, str): - msg = "message is not a string" - raise TypeError(msg) - message_data = message_str.encode() - - async def ack(*, _message_id: int = message_id) -> None: - if self._write_pool is None: - msg = "Call startup before starting listening." - raise ValueError(msg) - async with self._write_pool.acquire() as conn, conn.cursor() as cursor: - await cursor.execute(DELETE_MESSAGE_QUERY.format(self.table_name), (_message_id,)) - - yield AckableMessage(data=message_data, ack=ack) + if payload == POLL_NOW: + next_poll = loop.time() + continue + claimed = await self._claim(CLAIM_MESSAGE_QUERY.format(self.table_name), (int(payload),)) + if claimed is not None: + yield self._ackable(claimed) except Exception: logger.exception("Error processing message") continue + + async def _claim(self, query: str, params: tuple[tp.Any, ...] = ()) -> tuple[tp.Any, ...] | None: + """Run a claim query and return the claimed (id, message) row, if any.""" + if self._write_pool is None: + msg = "Call startup before starting listening." + raise ValueError(msg) + async with self._write_pool.acquire() as conn, conn.cursor() as cursor: + await cursor.execute(query, params) + return tp.cast("tuple[tp.Any, ...] | None", await cursor.fetchone()) + + def _ackable(self, claimed: tuple[tp.Any, ...]) -> AckableMessage: + """Wrap a claimed message; acknowledging it deletes the row.""" + message_id = int(claimed[0]) + message_str = claimed[1] + if not isinstance(message_str, str): + msg = "message is not a string" + raise TypeError(msg) + + async def ack() -> None: + if self._write_pool is None: + msg = "Call startup before starting listening." + raise ValueError(msg) + async with self._write_pool.acquire() as conn, conn.cursor() as cursor: + await cursor.execute(DELETE_MESSAGE_QUERY.format(self.table_name), (message_id,)) + + return AckableMessage(data=message_str.encode(), ack=ack) diff --git a/src/taskiq_pg/aiopg/queries.py b/src/taskiq_pg/aiopg/queries.py index 30431dc..ef5ece1 100644 --- a/src/taskiq_pg/aiopg/queries.py +++ b/src/taskiq_pg/aiopg/queries.py @@ -99,3 +99,18 @@ CLAIM_MESSAGE_QUERY = "UPDATE {} SET status = 'processing' WHERE id = %s AND status = 'pending' RETURNING id, message" DELETE_MESSAGE_QUERY = "DELETE FROM {} WHERE id = %s" + +CREATE_PENDING_INDEX_QUERY = "CREATE INDEX IF NOT EXISTS {index} ON {table} (id) WHERE status = 'pending'" + +CLAIM_NEXT_READY_MESSAGE_QUERY = """ +UPDATE {table} SET status = 'processing' +WHERE id = ( + SELECT id FROM {table} + WHERE status = 'pending' + AND created_at + make_interval(secs => COALESCE((labels->>'delay')::double precision, 0)) <= now() + ORDER BY id + LIMIT 1 + FOR UPDATE SKIP LOCKED +) +RETURNING id, message +""" diff --git a/tests/integration/test_polling.py b/tests/integration/test_polling.py index 012e878..da6e1c0 100644 --- a/tests/integration/test_polling.py +++ b/tests/integration/test_polling.py @@ -7,13 +7,14 @@ import pytest from taskiq import AckableMessage, 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 -Broker: tp.TypeAlias = AsyncpgBroker | PsycopgBroker | PSQLPyBroker -BROKERS: list[tp.Any] = [AsyncpgBroker, PsycopgBroker, PSQLPyBroker] +Broker: tp.TypeAlias = AsyncpgBroker | PsycopgBroker | PSQLPyBroker | AiopgBroker +BROKERS: list[tp.Any] = [AsyncpgBroker, PsycopgBroker, PSQLPyBroker, AiopgBroker] def unique_names() -> dict[str, str]: From cff6ed3fb07c5b92cdc16394e0385c266c9f6434 Mon Sep 17 00:00:00 2001 From: Dmitry Anfimov Date: Wed, 25 Nov 2026 19:50:03 +0100 Subject: [PATCH 05/10] test: isolate reconnect and keepalive tests in their own tables With polling, a listening broker also claims pending rows left in the shared taskiq_messages table by other tests, so tests that expect a specific message got someone else's. --- tests/integration/test_aiopg_reconnect.py | 6 +++--- tests/integration/test_asyncpg_reconnect.py | 2 +- tests/integration/test_listen_keepalive.py | 5 +++-- tests/integration/test_listener_reconnect.py | 2 +- tests/integration/test_psqlpy_reconnect.py | 4 ++-- tests/integration/test_psycopg_reconnect.py | 8 ++++---- 6 files changed, 14 insertions(+), 13 deletions(-) diff --git a/tests/integration/test_aiopg_reconnect.py b/tests/integration/test_aiopg_reconnect.py index f926c6c..448bfb3 100644 --- a/tests/integration/test_aiopg_reconnect.py +++ b/tests/integration/test_aiopg_reconnect.py @@ -20,7 +20,7 @@ async def test_when_reconnect_attempts_fail__then_listener_keeps_retrying( ) -> None: # given channel = f"reconnect_{uuid.uuid4().hex}" - broker = AiopgBroker(dsn=pg_dsn, channel_name=channel) + broker = AiopgBroker(dsn=pg_dsn, channel_name=channel, table_name=channel) await broker.startup() connect_listener = broker._connect_listener # noqa: SLF001 attempts = 0 @@ -71,7 +71,7 @@ async def test_when_supplied_read_connection_was_terminated__then_warning_is_log # given channel = f"reconnect_{uuid.uuid4().hex}" read_connection = await aiopg.connect(pg_dsn) - broker = AiopgBroker(dsn=pg_dsn, channel_name=channel, read_connection=read_connection) + broker = AiopgBroker(dsn=pg_dsn, channel_name=channel, table_name=channel, read_connection=read_connection) await broker.startup() try: with caplog.at_level("WARNING", logger="taskiq.aiopg_broker"): @@ -98,7 +98,7 @@ async def test_when_shutdown_during_reconnect__then_reconnect_is_cancelled( ) -> None: # given channel = f"reconnect_{uuid.uuid4().hex}" - broker = AiopgBroker(dsn=pg_dsn, channel_name=channel) + broker = AiopgBroker(dsn=pg_dsn, channel_name=channel, table_name=channel) await broker.startup() connecting = asyncio.Event() cancelled = asyncio.Event() diff --git a/tests/integration/test_asyncpg_reconnect.py b/tests/integration/test_asyncpg_reconnect.py index ffdda37..a57b68f 100644 --- a/tests/integration/test_asyncpg_reconnect.py +++ b/tests/integration/test_asyncpg_reconnect.py @@ -40,7 +40,7 @@ async def test_listener_receives_messages_after_connection_loss( failures: int, ) -> None: """Resume receiving tasks after disconnection, including temporary database unavailability.""" - broker = AsyncpgBroker(dsn=pg_dsn) + broker = AsyncpgBroker(dsn=pg_dsn, table_name=f"reconnect_{uuid.uuid4().hex}") await broker.startup() original = broker._read_conn # noqa: SLF001 assert original is not None diff --git a/tests/integration/test_listen_keepalive.py b/tests/integration/test_listen_keepalive.py index 59616ee..602a6b7 100644 --- a/tests/integration/test_listen_keepalive.py +++ b/tests/integration/test_listen_keepalive.py @@ -72,7 +72,7 @@ async def test_when_keepalive_query_hangs__then_listener_reconnects( ) -> None: # given channel = f"keepalive_{uuid.uuid4().hex}" - broker = broker_class(dsn=pg_dsn, channel_name=channel, **FAST_KEEPALIVE) + broker = broker_class(dsn=pg_dsn, channel_name=channel, table_name=channel, **FAST_KEEPALIVE) keepalive_query = broker._keepalive_query # noqa: SLF001 hung = asyncio.Event() @@ -118,6 +118,7 @@ async def _listen_backends_after_idle_period( broker = broker_class( dsn=pg_dsn, channel_name=channel, + table_name=channel, read_kwargs=read_kwargs, listen_keepalive_interval=keepalive_interval, listen_keepalive_timeout=1.0, @@ -181,7 +182,7 @@ async def test_when_psycopg_keepalive_query_ignores_cancellation__then_hang_is_d """ # given channel = f"keepalive_{uuid.uuid4().hex}" - broker = PsycopgBroker(dsn=pg_dsn, channel_name=channel, **FAST_KEEPALIVE) + broker = PsycopgBroker(dsn=pg_dsn, channel_name=channel, table_name=channel, **FAST_KEEPALIVE) keepalive_query = broker._keepalive_query # noqa: SLF001 hung = asyncio.Event() diff --git a/tests/integration/test_listener_reconnect.py b/tests/integration/test_listener_reconnect.py index 6210cc8..da7710e 100644 --- a/tests/integration/test_listener_reconnect.py +++ b/tests/integration/test_listener_reconnect.py @@ -46,7 +46,7 @@ async def test_when_listen_connection_was_terminated__then_worker_received_next_ ) -> None: # given channel = f"reconnect_{uuid.uuid4().hex}" - broker = broker_class(dsn=pg_dsn, channel_name=channel) + broker = broker_class(dsn=pg_dsn, channel_name=channel, table_name=channel) await broker.startup() listener = broker.listen() task: asyncio.Task[tp.Any] = asyncio.create_task(listener.__anext__()) diff --git a/tests/integration/test_psqlpy_reconnect.py b/tests/integration/test_psqlpy_reconnect.py index af0ee2c..b89f33c 100644 --- a/tests/integration/test_psqlpy_reconnect.py +++ b/tests/integration/test_psqlpy_reconnect.py @@ -20,7 +20,7 @@ async def test_when_reconnect_attempts_fail__then_listener_keeps_retrying( ) -> None: # given channel = f"reconnect_{uuid.uuid4().hex}" - broker = PSQLPyBroker(dsn=pg_dsn, channel_name=channel) + broker = PSQLPyBroker(dsn=pg_dsn, channel_name=channel, table_name=channel) await broker.startup() start_listener = broker._start_listener # noqa: SLF001 attempts = 0 @@ -70,7 +70,7 @@ async def test_when_shutdown_during_reconnect__then_reconnect_is_cancelled( ) -> None: # given channel = f"reconnect_{uuid.uuid4().hex}" - broker = PSQLPyBroker(dsn=pg_dsn, channel_name=channel) + broker = PSQLPyBroker(dsn=pg_dsn, channel_name=channel, table_name=channel) await broker.startup() connecting = asyncio.Event() cancelled = asyncio.Event() diff --git a/tests/integration/test_psycopg_reconnect.py b/tests/integration/test_psycopg_reconnect.py index 989466c..ece3823 100644 --- a/tests/integration/test_psycopg_reconnect.py +++ b/tests/integration/test_psycopg_reconnect.py @@ -20,7 +20,7 @@ async def test_when_reconnect_attempts_fail__then_listener_keeps_retrying( ) -> None: # given channel = f"reconnect_{uuid.uuid4().hex}" - broker = PsycopgBroker(dsn=pg_dsn, channel_name=channel) + broker = PsycopgBroker(dsn=pg_dsn, channel_name=channel, table_name=channel) await broker.startup() connect_listener = broker._connect_listener # noqa: SLF001 attempts = 0 @@ -70,7 +70,7 @@ async def test_when_supplied_read_connection_was_terminated__then_error_is_raise # given channel = f"reconnect_{uuid.uuid4().hex}" read_connection = await psycopg.AsyncConnection.connect(pg_dsn, autocommit=True) - broker = PsycopgBroker(dsn=pg_dsn, channel_name=channel, read_connection=read_connection) + broker = PsycopgBroker(dsn=pg_dsn, channel_name=channel, table_name=channel, read_connection=read_connection) await broker.startup() listener = broker.listen() task: asyncio.Task[tp.Any] = asyncio.create_task(listener.__anext__()) @@ -98,7 +98,7 @@ async def test_when_broker_is_shut_down_while_listening__then_listener_stops_wit ) -> None: # given channel = f"reconnect_{uuid.uuid4().hex}" - broker = PsycopgBroker(dsn=pg_dsn, channel_name=channel) + broker = PsycopgBroker(dsn=pg_dsn, channel_name=channel, table_name=channel) await broker.startup() listener = broker.listen() task: asyncio.Task[tp.Any] = asyncio.create_task(listener.__anext__()) @@ -123,7 +123,7 @@ async def test_when_broker_is_shut_down_during_reconnect__then_reconnect_stops( ) -> None: # given channel = f"reconnect_{uuid.uuid4().hex}" - broker = PsycopgBroker(dsn=pg_dsn, channel_name=channel) + broker = PsycopgBroker(dsn=pg_dsn, channel_name=channel, table_name=channel) await broker.startup() attempts = 0 From becddd097c463ee9c79dba20cd62c112c8cdb212 Mon Sep 17 00:00:00 2001 From: Dmitry Anfimov Date: Wed, 25 Nov 2026 19:50:03 +0100 Subject: [PATCH 06/10] feat(psycopg): do not block kick() for the delay of a delayed message kick() with a delay label waited for the whole delay before returning, because the delayed NOTIFY was the only way the message could reach a worker. Workers now poll for messages whose delay has elapsed, so the NOTIFY is sent from a background task like in the other brokers, and pending ones are cancelled on shutdown. --- src/taskiq_pg/psycopg/broker.py | 11 ++++++++++- tests/integration/test_broker.py | 31 +++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/taskiq_pg/psycopg/broker.py b/src/taskiq_pg/psycopg/broker.py index 315b791..3127f82 100644 --- a/src/taskiq_pg/psycopg/broker.py +++ b/src/taskiq_pg/psycopg/broker.py @@ -12,6 +12,7 @@ from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, POLL_NOW, BasePostgresBroker from taskiq_pg._internal.retry import retry_delays +from taskiq_pg._internal.tasks import cancel_and_wait from taskiq_pg.psycopg.queries import ( CLAIM_MESSAGE_QUERY, CLAIM_NEXT_READY_MESSAGE_QUERY, @@ -181,6 +182,8 @@ def __init__( # noqa: PLR0913 self._read_conn = read_connection self._owns_read_conn = False + self._notify_tasks: set[asyncio.Task[None]] = set() + async def startup(self) -> None: """Initialize the broker.""" await super().startup() @@ -269,6 +272,8 @@ def _is_closing(self) -> bool: async def shutdown(self) -> None: """Close all connections on shutdown.""" self._closing = True + for task in list(self._notify_tasks): + await cancel_and_wait(task) await super().shutdown() if self._notifies_iter is not None: with suppress(RuntimeError): # RuntimeError: aclose(): asynchronous generator is already running @@ -317,7 +322,11 @@ async def kick(self, message: BrokerMessage) -> None: # The insert is committed once the connection is returned to the pool, # so a delayed NOTIFY sent from here never reaches a worker before the row is visible. - await self._schedule_notification(message_inserted_id, int(delay_value)) + # The NOTIFY is only the fast path: workers also poll for messages whose delay has elapsed, + # so the message is delivered even if this producer exits before sending it. + task = asyncio.create_task(self._schedule_notification(message_inserted_id, int(delay_value))) + self._notify_tasks.add(task) + task.add_done_callback(self._notify_tasks.discard) async def _schedule_notification(self, message_id: int, delay_seconds: int) -> None: """Schedule a notification to be sent after a delay.""" diff --git a/tests/integration/test_broker.py b/tests/integration/test_broker.py index 54f5697..a883f3c 100644 --- a/tests/integration/test_broker.py +++ b/tests/integration/test_broker.py @@ -1,4 +1,5 @@ import asyncio +import time import typing as tp import uuid @@ -178,3 +179,33 @@ async def test_when_delayed_message_was_published__then_worker_received_message( assert task.result().data == message.message finally: task.cancel() + + +@pytest.mark.integration +@pytest.mark.parametrize( + "broker", + [ + AsyncpgBroker, + PSQLPyBroker, + PsycopgBroker, + AiopgBroker, + ], + indirect=True, +) +async def test_when_delayed_message_was_published__then_kick_does_not_wait_for_the_delay( + broker, +) -> None: + # given + message: BrokerMessage = BrokerMessage( + task_id=uuid.uuid4().hex, + task_name="example:delayed_task", + message=b'{"hello":"later"}', + labels={"delay": 3}, + ) + + # when + started = time.monotonic() + await broker.kick(message) + + # then + assert time.monotonic() - started < 1, "kick() must return before the delay elapses" From 54ce92630503b7789e1502f1c67d2d3643267768 Mon Sep 17 00:00:00 2001 From: Dmitry Anfimov Date: Wed, 25 Nov 2026 20:17:47 +0100 Subject: [PATCH 07/10] fix: serialize schema setup of brokers that start at once Worker processes of one deployment start together, and concurrent CREATE TABLE / CREATE INDEX IF NOT EXISTS on a new table fail with a unique violation in the system catalogs, so some of them failed to start (taskiq restarted them). The race existed for the table before; the pending index made it more likely. Create the table and its indexes in one transaction that first takes an advisory lock derived from the table name, so brokers wait for each other. --- src/taskiq_pg/_internal/broker.py | 12 ++++++++++ src/taskiq_pg/aiopg/broker.py | 18 ++++++++++----- src/taskiq_pg/asyncpg/broker.py | 5 +++-- src/taskiq_pg/psqlpy/broker.py | 9 ++++---- src/taskiq_pg/psycopg/broker.py | 9 ++++++-- tests/integration/test_schema_setup.py | 31 ++++++++++++++++++++++++++ 6 files changed, 71 insertions(+), 13 deletions(-) create mode 100644 tests/integration/test_schema_setup.py diff --git a/src/taskiq_pg/_internal/broker.py b/src/taskiq_pg/_internal/broker.py index 88c060a..48b2e53 100644 --- a/src/taskiq_pg/_internal/broker.py +++ b/src/taskiq_pg/_internal/broker.py @@ -1,4 +1,5 @@ import abc +import hashlib import typing as tp from taskiq import AsyncBroker, AsyncResultBackend @@ -82,3 +83,14 @@ def __init__( # noqa: PLR0913 POLL_NOW = "" """Queue item that asks a listening worker to poll for pending messages right away (never a message id).""" + + +def schema_lock_query(table_name: str) -> str: + """ + Return a query that serializes schema setup of one messages table. + + Run it first in the transaction that creates the table and its indexes: brokers that start at the same + time then wait for each other instead of failing on concurrent `CREATE ... IF NOT EXISTS`. + """ + digest = hashlib.sha256(f"taskiq_pg:messages:{table_name}".encode()).digest() + return f"SELECT pg_advisory_xact_lock({int.from_bytes(digest[:8], 'big', signed=True)})" diff --git a/src/taskiq_pg/aiopg/broker.py b/src/taskiq_pg/aiopg/broker.py index 910a883..1b0cd22 100644 --- a/src/taskiq_pg/aiopg/broker.py +++ b/src/taskiq_pg/aiopg/broker.py @@ -7,7 +7,7 @@ import aiopg from taskiq import AckableMessage, AsyncResultBackend, BrokerMessage -from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, POLL_NOW, BasePostgresBroker +from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, POLL_NOW, BasePostgresBroker, schema_lock_query from taskiq_pg._internal.retry import retry_delays from taskiq_pg._internal.tasks import cancel_and_wait, run_until_first_done from taskiq_pg.aiopg.queries import ( @@ -181,10 +181,18 @@ async def startup(self) -> None: if self._write_pool is None: self._write_pool = await aiopg.create_pool(self.dsn, **self.write_kwargs) async with self._write_pool.acquire() as conn, conn.cursor() as cursor: - await cursor.execute(CREATE_MESSAGE_TABLE_QUERY.format(self.table_name)) - await cursor.execute( - CREATE_PENDING_INDEX_QUERY.format(index=f"{self.table_name}_pending_idx", table=self.table_name), - ) + # aiopg connections are always in autocommit mode, so the transaction is explicit. + await cursor.execute("BEGIN") + try: + await cursor.execute(schema_lock_query(self.table_name)) + await cursor.execute(CREATE_MESSAGE_TABLE_QUERY.format(self.table_name)) + await cursor.execute( + CREATE_PENDING_INDEX_QUERY.format(index=f"{self.table_name}_pending_idx", table=self.table_name), + ) + except BaseException: + await cursor.execute("ROLLBACK") + raise + await cursor.execute("COMMIT") if self._owns_read_conn: self._read_conn = await self._connect_listener() elif self._read_conn is not None: diff --git a/src/taskiq_pg/asyncpg/broker.py b/src/taskiq_pg/asyncpg/broker.py index 6e8cd75..d5e13bb 100644 --- a/src/taskiq_pg/asyncpg/broker.py +++ b/src/taskiq_pg/asyncpg/broker.py @@ -7,7 +7,7 @@ import asyncpg from taskiq import AckableMessage, AsyncResultBackend, BrokerMessage -from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, POLL_NOW, BasePostgresBroker +from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, POLL_NOW, BasePostgresBroker, schema_lock_query from taskiq_pg._internal.retry import retry_delays from taskiq_pg._internal.tasks import cancel_and_wait from taskiq_pg.asyncpg.queries import ( @@ -179,7 +179,8 @@ async def startup(self) -> None: self._listener_disconnected = asyncio.Event() if self._write_pool is None: self._write_pool = await asyncpg.create_pool(self.dsn, **self.write_kwargs) - async with self._write_pool.acquire() as conn: + async with self._write_pool.acquire() as conn, conn.transaction(): + await conn.execute(schema_lock_query(self.table_name)) await conn.execute(CREATE_MESSAGE_TABLE_QUERY.format(self.table_name)) await conn.execute( CREATE_PENDING_INDEX_QUERY.format(index=f"{self.table_name}_pending_idx", table=self.table_name), diff --git a/src/taskiq_pg/psqlpy/broker.py b/src/taskiq_pg/psqlpy/broker.py index 9fe9d28..e2a6b84 100644 --- a/src/taskiq_pg/psqlpy/broker.py +++ b/src/taskiq_pg/psqlpy/broker.py @@ -11,7 +11,7 @@ from psqlpy.extra_types import JSONB from taskiq import AckableMessage, AsyncResultBackend, BrokerMessage -from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, POLL_NOW, BasePostgresBroker +from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, POLL_NOW, BasePostgresBroker, schema_lock_query from taskiq_pg._internal.retry import retry_delays from taskiq_pg._internal.tasks import cancel_and_wait, run_until_first_done from taskiq_pg.psqlpy.queries import ( @@ -114,9 +114,10 @@ async def startup(self) -> None: ) # create messages table if it doesn't exist - async with self._write_pool.acquire() as conn: - await conn.execute(CREATE_MESSAGE_TABLE_QUERY.format(self.table_name)) - await conn.execute( + async with self._write_pool.acquire() as conn, conn.transaction() as transaction: + await transaction.execute(schema_lock_query(self.table_name)) + await transaction.execute(CREATE_MESSAGE_TABLE_QUERY.format(self.table_name)) + await transaction.execute( CREATE_PENDING_INDEX_QUERY.format(index=f"{self.table_name}_pending_idx", table=self.table_name), ) diff --git a/src/taskiq_pg/psycopg/broker.py b/src/taskiq_pg/psycopg/broker.py index 3127f82..23ee14a 100644 --- a/src/taskiq_pg/psycopg/broker.py +++ b/src/taskiq_pg/psycopg/broker.py @@ -10,7 +10,7 @@ from psycopg_pool import AsyncConnectionPool from taskiq import AckableMessage, AsyncResultBackend, BrokerMessage -from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, POLL_NOW, BasePostgresBroker +from taskiq_pg._internal.broker import LISTEN_KEEPALIVE_QUERY, POLL_NOW, BasePostgresBroker, schema_lock_query from taskiq_pg._internal.retry import retry_delays from taskiq_pg._internal.tasks import cancel_and_wait from taskiq_pg.psycopg.queries import ( @@ -199,7 +199,12 @@ async def startup(self) -> None: if self._write_pool.closed: await self._write_pool.open() - async with self._write_pool.connection() as connection, connection.cursor() as cursor: + async with ( + self._write_pool.connection() as connection, + connection.transaction(), + connection.cursor() as cursor, + ): + await cursor.execute(schema_lock_query(self.table_name)) await cursor.execute(sql.SQL(CREATE_MESSAGE_TABLE_QUERY).format(sql.Identifier(self.table_name))) await cursor.execute( sql.SQL(CREATE_PENDING_INDEX_QUERY).format( diff --git a/tests/integration/test_schema_setup.py b/tests/integration/test_schema_setup.py new file mode 100644 index 0000000..a073c14 --- /dev/null +++ b/tests/integration/test_schema_setup.py @@ -0,0 +1,31 @@ +import asyncio +import typing as tp +import uuid + +import pytest + +from taskiq_pg.aiopg import AiopgBroker +from taskiq_pg.asyncpg import AsyncpgBroker +from taskiq_pg.psqlpy import PSQLPyBroker +from taskiq_pg.psycopg import PsycopgBroker + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", [AsyncpgBroker, PsycopgBroker, PSQLPyBroker, AiopgBroker]) +async def test_when_many_brokers_start_at_once_on_a_new_table__then_all_of_them_start( + pg_dsn: str, + broker_class: type[tp.Any], +) -> None: + """Workers of one deployment start together; concurrent schema setup must not make any of them fail.""" + # given + names = {"table_name": f"setup_{uuid.uuid4().hex[:12]}", "channel_name": f"setup_{uuid.uuid4().hex[:12]}"} + brokers = [broker_class(dsn=pg_dsn, **names) for _ in range(8)] + + # when + results = await asyncio.gather(*(broker.startup() for broker in brokers), return_exceptions=True) + + # then + try: + assert [r for r in results if isinstance(r, BaseException)] == [] + finally: + await asyncio.gather(*(broker.shutdown() for broker in brokers), return_exceptions=True) From 1ffc616507b1a7b7f8bff10ae029d55325aab35c Mon Sep 17 00:00:00 2001 From: Dmitry Anfimov Date: Wed, 25 Nov 2026 23:20:32 +0100 Subject: [PATCH 08/10] test: keep concurrent-startup brokers below max_connections Eight asyncpg brokers with the default pool (10 connections each) exhausted the CI server's connection slots. --- tests/integration/test_schema_setup.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/tests/integration/test_schema_setup.py b/tests/integration/test_schema_setup.py index a073c14..ddb474b 100644 --- a/tests/integration/test_schema_setup.py +++ b/tests/integration/test_schema_setup.py @@ -10,16 +10,26 @@ from taskiq_pg.psycopg import PsycopgBroker +# Small pools, so that eight brokers stay well below max_connections (asyncpg opens 10 connections by default). +SMALL_POOLS: list[tp.Any] = [ + pytest.param(AsyncpgBroker, {"min_size": 1, "max_size": 2}, id="AsyncpgBroker"), + pytest.param(PsycopgBroker, {"min_size": 1, "max_size": 2}, id="PsycopgBroker"), + pytest.param(PSQLPyBroker, {"max_db_pool_size": 2}, id="PSQLPyBroker"), + pytest.param(AiopgBroker, {"minsize": 1, "maxsize": 2}, id="AiopgBroker"), +] + + @pytest.mark.integration -@pytest.mark.parametrize("broker_class", [AsyncpgBroker, PsycopgBroker, PSQLPyBroker, AiopgBroker]) +@pytest.mark.parametrize(("broker_class", "write_kwargs"), SMALL_POOLS) async def test_when_many_brokers_start_at_once_on_a_new_table__then_all_of_them_start( pg_dsn: str, broker_class: type[tp.Any], + write_kwargs: dict[str, tp.Any], ) -> None: """Workers of one deployment start together; concurrent schema setup must not make any of them fail.""" # given names = {"table_name": f"setup_{uuid.uuid4().hex[:12]}", "channel_name": f"setup_{uuid.uuid4().hex[:12]}"} - brokers = [broker_class(dsn=pg_dsn, **names) for _ in range(8)] + brokers = [broker_class(dsn=pg_dsn, write_kwargs=write_kwargs, **names) for _ in range(8)] # when results = await asyncio.gather(*(broker.startup() for broker in brokers), return_exceptions=True) From f6ad03ca1cd4044467b43a6f044e5822259c4629 Mon Sep 17 00:00:00 2001 From: Dmitry Anfimov Date: Wed, 25 Nov 2026 23:20:32 +0100 Subject: [PATCH 09/10] fix: tolerate malformed delay labels when polling The poll query cast every pending row's delay label to a number, so one label that could not be cast ("abc") or overflowed make_interval made the query fail on every poll. Polling stopped for all messages behind that row, and a psycopg worker stopped receiving messages at all. A label that is not a plain non-negative number now counts as no delay; an absurdly large one is never ready. --- src/taskiq_pg/aiopg/queries.py | 7 ++++++- src/taskiq_pg/asyncpg/queries.py | 7 ++++++- src/taskiq_pg/psqlpy/queries.py | 7 ++++++- src/taskiq_pg/psycopg/queries.py | 7 ++++++- 4 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/taskiq_pg/aiopg/queries.py b/src/taskiq_pg/aiopg/queries.py index ef5ece1..7112254 100644 --- a/src/taskiq_pg/aiopg/queries.py +++ b/src/taskiq_pg/aiopg/queries.py @@ -107,7 +107,12 @@ WHERE id = ( SELECT id FROM {table} WHERE status = 'pending' - AND created_at + make_interval(secs => COALESCE((labels->>'delay')::double precision, 0)) <= now() + AND created_at + make_interval(secs => CASE + -- a label that is not a plain number must not break the query for every other row + WHEN labels->>'delay' ~ '^[0-9]{{1,10}}(\\.[0-9]+)?$' THEN (labels->>'delay')::double precision + WHEN labels->>'delay' ~ '^[0-9]+(\\.[0-9]+)?$' THEN 1e10 -- over 300 years: never ready + ELSE 0 + END) <= now() ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED diff --git a/src/taskiq_pg/asyncpg/queries.py b/src/taskiq_pg/asyncpg/queries.py index 2eb8864..ce90015 100644 --- a/src/taskiq_pg/asyncpg/queries.py +++ b/src/taskiq_pg/asyncpg/queries.py @@ -107,7 +107,12 @@ WHERE id = ( SELECT id FROM {table} WHERE status = 'pending' - AND created_at + make_interval(secs => COALESCE((labels->>'delay')::double precision, 0)) <= now() + AND created_at + make_interval(secs => CASE + -- a label that is not a plain number must not break the query for every other row + WHEN labels->>'delay' ~ '^[0-9]{{1,10}}(\\.[0-9]+)?$' THEN (labels->>'delay')::double precision + WHEN labels->>'delay' ~ '^[0-9]+(\\.[0-9]+)?$' THEN 1e10 -- over 300 years: never ready + ELSE 0 + END) <= now() ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED diff --git a/src/taskiq_pg/psqlpy/queries.py b/src/taskiq_pg/psqlpy/queries.py index 05b4dd3..87bcf11 100644 --- a/src/taskiq_pg/psqlpy/queries.py +++ b/src/taskiq_pg/psqlpy/queries.py @@ -107,7 +107,12 @@ WHERE id = ( SELECT id FROM {table} WHERE status = 'pending' - AND created_at + make_interval(secs => COALESCE((labels->>'delay')::double precision, 0)) <= now() + AND created_at + make_interval(secs => CASE + -- a label that is not a plain number must not break the query for every other row + WHEN labels->>'delay' ~ '^[0-9]{{1,10}}(\\.[0-9]+)?$' THEN (labels->>'delay')::double precision + WHEN labels->>'delay' ~ '^[0-9]+(\\.[0-9]+)?$' THEN 1e10 -- over 300 years: never ready + ELSE 0 + END) <= now() ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED diff --git a/src/taskiq_pg/psycopg/queries.py b/src/taskiq_pg/psycopg/queries.py index 859ea5b..a4bfaeb 100644 --- a/src/taskiq_pg/psycopg/queries.py +++ b/src/taskiq_pg/psycopg/queries.py @@ -107,7 +107,12 @@ WHERE id = ( SELECT id FROM {table} WHERE status = 'pending' - AND created_at + make_interval(secs => COALESCE((labels->>'delay')::double precision, 0)) <= now() + AND created_at + make_interval(secs => CASE + -- a label that is not a plain number must not break the query for every other row + WHEN labels->>'delay' ~ '^[0-9]{{1,10}}(\\.[0-9]+)?$' THEN (labels->>'delay')::double precision + WHEN labels->>'delay' ~ '^[0-9]+(\\.[0-9]+)?$' THEN 1e10 -- over 300 years: never ready + ELSE 0 + END) <= now() ORDER BY id LIMIT 1 FOR UPDATE SKIP LOCKED From 7cbe62220d3a2f279c348fdbbc9b6f3e096a5a54 Mon Sep 17 00:00:00 2001 From: Dmitry Anfimov Date: Wed, 25 Nov 2026 23:20:32 +0100 Subject: [PATCH 10/10] fix: parse the delay label before inserting the message kick() inserted the message before int(delay) raised, leaving a row the caller believed was not sent; polling would now execute it. --- src/taskiq_pg/aiopg/broker.py | 9 ++++-- src/taskiq_pg/asyncpg/broker.py | 8 +++-- src/taskiq_pg/psqlpy/broker.py | 8 +++-- src/taskiq_pg/psycopg/broker.py | 9 ++++-- tests/integration/test_polling.py | 53 +++++++++++++++++++++++++++++++ 5 files changed, 75 insertions(+), 12 deletions(-) diff --git a/src/taskiq_pg/aiopg/broker.py b/src/taskiq_pg/aiopg/broker.py index 1b0cd22..7accc20 100644 --- a/src/taskiq_pg/aiopg/broker.py +++ b/src/taskiq_pg/aiopg/broker.py @@ -308,6 +308,10 @@ async def kick(self, message: BrokerMessage) -> None: msg = "Please run startup before kicking." raise ValueError(msg) + # Parse the delay before inserting, so a malformed label does not leave a message behind. + delay_value = message.labels.get("delay") + delay_seconds = None if delay_value is None else int(delay_value) + async with self._write_pool.acquire() as conn, conn.cursor() as cursor: await cursor.execute( INSERT_MESSAGE_QUERY.format(self.table_name), @@ -319,13 +323,12 @@ async def kick(self, message: BrokerMessage) -> None: raise RuntimeError(msg) message_id = int(row[0]) - delay_value = message.labels.get("delay") - if delay_value is None: + if delay_seconds is None: # Send a NOTIFY with the message ID as payload await cursor.execute(f"NOTIFY {self.channel_name}, %s", (str(message_id),)) return - task = asyncio.create_task(self._schedule_notification(message_id, int(delay_value))) + task = asyncio.create_task(self._schedule_notification(message_id, delay_seconds)) self._notify_tasks.add(task) task.add_done_callback(self._notify_tasks.discard) diff --git a/src/taskiq_pg/asyncpg/broker.py b/src/taskiq_pg/asyncpg/broker.py index d5e13bb..632490d 100644 --- a/src/taskiq_pg/asyncpg/broker.py +++ b/src/taskiq_pg/asyncpg/broker.py @@ -325,6 +325,10 @@ async def kick(self, message: BrokerMessage) -> None: msg = "Please run startup before kicking." raise ValueError(msg) + # Parse the delay before inserting, so a malformed label does not leave a message behind. + delay_value = message.labels.get("delay") + delay_seconds = None if delay_value is None else int(delay_value) + async with self._write_pool.acquire() as conn: # Insert the message into the database message_inserted_id = tp.cast( @@ -338,9 +342,7 @@ async def kick(self, message: BrokerMessage) -> None: ), ) - delay_value = message.labels.get("delay") - if delay_value is not None: - delay_seconds = int(delay_value) + if delay_seconds is not None: _ = asyncio.create_task( # noqa: RUF006 self._schedule_notification(message_inserted_id, delay_seconds), ) diff --git a/src/taskiq_pg/psqlpy/broker.py b/src/taskiq_pg/psqlpy/broker.py index e2a6b84..a82d28d 100644 --- a/src/taskiq_pg/psqlpy/broker.py +++ b/src/taskiq_pg/psqlpy/broker.py @@ -246,6 +246,10 @@ async def kick(self, message: BrokerMessage) -> None: :param message: Message to send. """ + # Parse the delay before inserting, so a malformed label does not leave a message behind. + delay_value = message.labels.get("delay") + delay_seconds = None if delay_value is None else int(delay_value) + async with self._write_pool.acquire() as conn: # insert message into db table message_inserted_id = tp.cast( @@ -261,9 +265,7 @@ async def kick(self, message: BrokerMessage) -> None: ), ) - delay_value = tp.cast("str | None", message.labels.get("delay")) - if delay_value is not None: - delay_seconds = int(delay_value) + if delay_seconds is not None: asyncio.create_task( # noqa: RUF006 self._schedule_notification(message_inserted_id, delay_seconds), ) diff --git a/src/taskiq_pg/psycopg/broker.py b/src/taskiq_pg/psycopg/broker.py index 23ee14a..29f6dc7 100644 --- a/src/taskiq_pg/psycopg/broker.py +++ b/src/taskiq_pg/psycopg/broker.py @@ -297,6 +297,10 @@ async def kick(self, message: BrokerMessage) -> None: :param message: Message to send. """ + # Parse the delay before inserting, so a malformed label does not leave a message behind. + delay_value = message.labels.get("delay") + delay_seconds = None if delay_value is None else int(delay_value) + async with self._write_pool.connection() as connection, connection.cursor() as cursor: # insert message into db table await cursor.execute( @@ -314,8 +318,7 @@ async def kick(self, message: BrokerMessage) -> None: raise RuntimeError(msg) message_inserted_id = int(row[0]) - delay_value = tp.cast("str | None", message.labels.get("delay")) - if delay_value is None: + if delay_seconds is None: # Send NOTIFY with message ID as payload await cursor.execute( sql.SQL("NOTIFY {}, {}").format( @@ -329,7 +332,7 @@ async def kick(self, message: BrokerMessage) -> None: # so a delayed NOTIFY sent from here never reaches a worker before the row is visible. # The NOTIFY is only the fast path: workers also poll for messages whose delay has elapsed, # so the message is delivered even if this producer exits before sending it. - task = asyncio.create_task(self._schedule_notification(message_inserted_id, int(delay_value))) + 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) diff --git a/tests/integration/test_polling.py b/tests/integration/test_polling.py index da6e1c0..b28cf69 100644 --- a/tests/integration/test_polling.py +++ b/tests/integration/test_polling.py @@ -195,3 +195,56 @@ async def test_when_broker_starts__then_pending_index_is_created( assert "WHERE (status = 'pending'::text)" in definition finally: await broker.shutdown() + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", BROKERS) +async def test_when_pending_rows_have_malformed_delay_labels__then_polling_still_claims_messages( + pg_dsn: str, + connection: asyncpg.Connection, + broker_class: type[Broker], +) -> None: + # given + names = unique_names() + table = names["table_name"] + broker = broker_class(dsn=pg_dsn, poll_interval=0.2, **names) + await broker.startup() + await insert_pending(connection, table, '{"label":"text"}', {"delay": "abc"}) + await insert_pending(connection, table, '{"label":"negative"}', {"delay": "-3"}) + await insert_pending(connection, table, '{"label":"huge"}', {"delay": "9" * 400}) + await insert_pending(connection, table, '{"label":"none"}', {}) + listener = broker.listen() + try: + # when + received = await take(listener, 3, timeout=5) + + # then + assert received == [b'{"label":"text"}', b'{"label":"negative"}', b'{"label":"none"}'] + pending = await connection.fetchval(f"SELECT message FROM {table} WHERE status = 'pending'") # noqa: S608 + assert pending == '{"label":"huge"}' + finally: + await listener.aclose() + await broker.shutdown() + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", BROKERS) +async def test_when_delay_label_is_malformed__then_kick_fails_without_inserting_the_message( + pg_dsn: str, + connection: asyncpg.Connection, + broker_class: type[Broker], +) -> None: + # given + names = unique_names() + broker = broker_class(dsn=pg_dsn, **names) + await broker.startup() + message = BrokerMessage(task_id=uuid.uuid4().hex, task_name="example:bad", message=b"{}", labels={"delay": "abc"}) + try: + # when + with pytest.raises(ValueError, match="invalid literal"): + await broker.kick(message) + + # then + assert await connection.fetchval(f"SELECT count(*) FROM {names['table_name']}") == 0 # noqa: S608 + finally: + await broker.shutdown()