From 54aa0110bc9c1a0d47aa50587aed628c75153524 Mon Sep 17 00:00:00 2001 From: Dmitry Anfimov Date: Wed, 25 Nov 2026 20:02:38 +0100 Subject: [PATCH 1/5] feat(asyncpg): optional at-least-once delivery with processing_timeout A claimed message whose worker died before acknowledging it (kill -9, or a claim whose reply was lost in a database restart) stayed in 'processing' forever, and max_retry_attempts was not used at all. Add processing_timeout (default None: at-most-once, as before). When set, a message claimed longer ago than the timeout is returned to the queue on the next poll, up to max_retry_attempts claims; after that it is marked as 'failed' and a warning is logged. Claims record claimed_at and count attempts in two new columns, which startup adds to existing tables; rows stuck before the upgrade are timed from created_at. Delivery can then repeat, so tasks must be idempotent and the timeout longer than the longest task. The psqlpy MessageRow gets the new columns as optional fields, so psqlpy brokers keep reading a table already migrated by another broker. --- src/taskiq_pg/_internal/broker.py | 16 +- src/taskiq_pg/aiopg/broker.py | 8 + src/taskiq_pg/asyncpg/broker.py | 49 +++++ src/taskiq_pg/asyncpg/queries.py | 31 ++- src/taskiq_pg/psqlpy/broker.py | 6 + src/taskiq_pg/psycopg/broker.py | 8 + tests/integration/test_processing_timeout.py | 193 +++++++++++++++++++ tests/unit/test_listen_keepalive_params.py | 30 +++ 8 files changed, 338 insertions(+), 3 deletions(-) create mode 100644 tests/integration/test_processing_timeout.py diff --git a/src/taskiq_pg/_internal/broker.py b/src/taskiq_pg/_internal/broker.py index 48b2e53..00e621a 100644 --- a/src/taskiq_pg/_internal/broker.py +++ b/src/taskiq_pg/_internal/broker.py @@ -31,6 +31,7 @@ def __init__( # noqa: PLR0913 listen_keepalive_interval: float | None = 30.0, listen_keepalive_timeout: float = 5.0, poll_interval: float = 5.0, + processing_timeout: float | None = None, ) -> None: """ Construct a new broker. @@ -41,7 +42,8 @@ def __init__( # noqa: PLR0913 task_id_generator: Custom task_id generator. channel_name: Name of the channel to listen on. table_name: Name of the table to store messages. - max_retry_attempts: Maximum number of message processing attempts. + max_retry_attempts: With processing_timeout set, how many times a message may be claimed + before it is marked as failed instead of being delivered again. read_kwargs: Additional arguments for read connection creation. write_kwargs: Additional arguments for write pool creation. listen_keepalive_interval: How often, in seconds, to run a query on the broker-owned LISTEN @@ -52,6 +54,11 @@ def __init__( # noqa: PLR0913 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. + processing_timeout: Enables at-least-once delivery. A claimed message that is neither acknowledged + nor rejected within this many seconds (for example, because its worker died) is delivered + again, up to max_retry_attempts times. Tasks must then be idempotent, and the timeout must be + longer than the longest task. None (the default) keeps at-most-once delivery: such a message + stays in the 'processing' state. """ if listen_keepalive_interval is not None and listen_keepalive_interval <= 0: msg = "listen_keepalive_interval must be positive or None" @@ -62,6 +69,12 @@ def __init__( # noqa: PLR0913 if poll_interval <= 0: msg = "poll_interval must be positive" raise ValueError(msg) + if processing_timeout is not None and processing_timeout <= 0: + msg = "processing_timeout must be positive or None" + raise ValueError(msg) + if max_retry_attempts < 1: + msg = "max_retry_attempts must be at least 1" + raise ValueError(msg) super().__init__( result_backend=result_backend, task_id_generator=task_id_generator, @@ -75,6 +88,7 @@ def __init__( # noqa: PLR0913 self.listen_keepalive_interval: float | None = listen_keepalive_interval self.listen_keepalive_timeout: float = listen_keepalive_timeout self.poll_interval: float = poll_interval + self.processing_timeout: float | None = processing_timeout self._queue: asyncio.Queue[str] | None = None diff --git a/src/taskiq_pg/aiopg/broker.py b/src/taskiq_pg/aiopg/broker.py index 7accc20..ccd7110 100644 --- a/src/taskiq_pg/aiopg/broker.py +++ b/src/taskiq_pg/aiopg/broker.py @@ -52,6 +52,7 @@ def __init__( listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., poll_interval: float = ..., + processing_timeout: float | None = ..., ) -> None: ... @tp.overload @@ -71,6 +72,7 @@ def __init__( listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., poll_interval: float = ..., + processing_timeout: float | None = ..., ) -> None: ... @tp.overload @@ -90,6 +92,7 @@ def __init__( listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., poll_interval: float = ..., + processing_timeout: float | None = ..., ) -> None: ... @tp.overload @@ -109,6 +112,7 @@ def __init__( listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., poll_interval: float = ..., + processing_timeout: float | None = ..., ) -> None: ... def __init__( # noqa: PLR0913 @@ -127,6 +131,7 @@ def __init__( # noqa: PLR0913 listen_keepalive_interval: float | None = 30.0, listen_keepalive_timeout: float = 5.0, poll_interval: float = 5.0, + processing_timeout: float | None = None, ) -> None: """ Construct a new AiopgBroker. @@ -147,6 +152,8 @@ def __init__( # noqa: PLR0913 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. + processing_timeout: Seconds after which an unacknowledged claimed message is delivered again + (at-least-once delivery); None keeps at-most-once delivery. """ super().__init__( dsn=dsn, @@ -160,6 +167,7 @@ def __init__( # noqa: PLR0913 listen_keepalive_interval=listen_keepalive_interval, listen_keepalive_timeout=listen_keepalive_timeout, poll_interval=poll_interval, + processing_timeout=processing_timeout, ) self._owns_write_pool = True diff --git a/src/taskiq_pg/asyncpg/broker.py b/src/taskiq_pg/asyncpg/broker.py index 632490d..295a6d5 100644 --- a/src/taskiq_pg/asyncpg/broker.py +++ b/src/taskiq_pg/asyncpg/broker.py @@ -11,12 +11,16 @@ from taskiq_pg._internal.retry import retry_delays from taskiq_pg._internal.tasks import cancel_and_wait from taskiq_pg.asyncpg.queries import ( + ADD_DELIVERY_COLUMNS_QUERY, CLAIM_MESSAGE_QUERY, CLAIM_NEXT_READY_MESSAGE_QUERY, CREATE_MESSAGE_TABLE_QUERY, CREATE_PENDING_INDEX_QUERY, + CREATE_PROCESSING_INDEX_QUERY, DELETE_MESSAGE_QUERY, + FAIL_EXHAUSTED_MESSAGES_QUERY, INSERT_MESSAGE_QUERY, + RELEASE_STALE_MESSAGES_QUERY, ) @@ -52,6 +56,7 @@ def __init__( listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., poll_interval: float = ..., + processing_timeout: float | None = ..., ) -> None: ... @tp.overload @@ -71,6 +76,7 @@ def __init__( listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., poll_interval: float = ..., + processing_timeout: float | None = ..., ) -> None: ... @tp.overload @@ -90,6 +96,7 @@ def __init__( listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., poll_interval: float = ..., + processing_timeout: float | None = ..., ) -> None: ... @tp.overload @@ -109,6 +116,7 @@ def __init__( listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., poll_interval: float = ..., + processing_timeout: float | None = ..., ) -> None: ... def __init__( # noqa: PLR0913 @@ -127,6 +135,7 @@ def __init__( # noqa: PLR0913 listen_keepalive_interval: float | None = 30.0, listen_keepalive_timeout: float = 5.0, poll_interval: float = 5.0, + processing_timeout: float | None = None, ) -> None: """ Construct a new AsyncpgBroker. @@ -147,6 +156,8 @@ def __init__( # noqa: PLR0913 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. + processing_timeout: Seconds after which an unacknowledged claimed message is delivered again + (at-least-once delivery); None keeps at-most-once delivery. """ super().__init__( dsn=dsn, @@ -160,6 +171,7 @@ def __init__( # noqa: PLR0913 listen_keepalive_interval=listen_keepalive_interval, listen_keepalive_timeout=listen_keepalive_timeout, poll_interval=poll_interval, + processing_timeout=processing_timeout, ) self._owns_write_pool = True @@ -182,9 +194,17 @@ async def startup(self) -> None: 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(ADD_DELIVERY_COLUMNS_QUERY.format(table=self.table_name)) await conn.execute( CREATE_PENDING_INDEX_QUERY.format(index=f"{self.table_name}_pending_idx", table=self.table_name), ) + if self.processing_timeout is not None: + await conn.execute( + CREATE_PROCESSING_INDEX_QUERY.format( + index=f"{self.table_name}_processing_idx", + table=self.table_name, + ), + ) await self._connect_listener() self._listener_task = asyncio.create_task(self._restore_listener()) @@ -383,6 +403,7 @@ async def listen(self) -> AsyncGenerator[AckableMessage, None]: try: if loop.time() >= next_poll: next_poll = loop.time() + self.poll_interval + await self._release_stale_messages() while (claimed := await self._claim_next_ready()) is not None: yield self._ackable(claimed) continue @@ -416,6 +437,34 @@ async def _claim_next_ready(self) -> asyncpg.Record | None: async with self._write_pool.acquire() as conn: return await conn.fetchrow(CLAIM_NEXT_READY_MESSAGE_QUERY.format(table=self.table_name)) + async def _release_stale_messages(self) -> None: + """ + With processing_timeout set, return messages claimed too long ago to the queue. + + A message whose attempts are exhausted is marked as failed instead. + """ + if self.processing_timeout is None or self._write_pool is None: + return + async with self._write_pool.acquire() as conn: + await conn.execute( + RELEASE_STALE_MESSAGES_QUERY.format(table=self.table_name), + self.processing_timeout, + self.max_retry_attempts, + ) + failed = await conn.fetch( + FAIL_EXHAUSTED_MESSAGES_QUERY.format(table=self.table_name), + self.processing_timeout, + self.max_retry_attempts, + ) + for row in failed: + logger.warning( + "Message %s (task %s, %s) was not acknowledged after %s attempts; marked as failed", + row["id"], + row["task_id"], + row["task_name"], + row["attempts"], + ) + def _ackable(self, claimed: asyncpg.Record) -> AckableMessage: """Wrap a claimed message; acknowledging it deletes the row.""" message_str = claimed["message"] diff --git a/src/taskiq_pg/asyncpg/queries.py b/src/taskiq_pg/asyncpg/queries.py index ce90015..0a6fed6 100644 --- a/src/taskiq_pg/asyncpg/queries.py +++ b/src/taskiq_pg/asyncpg/queries.py @@ -64,7 +64,11 @@ RETURNING id """ -CLAIM_MESSAGE_QUERY = "UPDATE {} SET status = 'processing' WHERE id = $1 AND status = 'pending' RETURNING id, message" +CLAIM_MESSAGE_QUERY = """ +UPDATE {} SET status = 'processing', claimed_at = now(), attempts = attempts + 1 +WHERE id = $1 AND status = 'pending' +RETURNING id, message +""" DELETE_MESSAGE_QUERY = "DELETE FROM {} WHERE id = $1" @@ -103,7 +107,7 @@ 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' +UPDATE {table} SET status = 'processing', claimed_at = now(), attempts = attempts + 1 WHERE id = ( SELECT id FROM {table} WHERE status = 'pending' @@ -119,3 +123,26 @@ ) RETURNING id, message """ + +ADD_DELIVERY_COLUMNS_QUERY = """ +ALTER TABLE {table} + ADD COLUMN IF NOT EXISTS claimed_at TIMESTAMP WITH TIME ZONE, + ADD COLUMN IF NOT EXISTS attempts INTEGER NOT NULL DEFAULT 0 +""" + +CREATE_PROCESSING_INDEX_QUERY = "CREATE INDEX IF NOT EXISTS {index} ON {table} (claimed_at) WHERE status = 'processing'" + +RELEASE_STALE_MESSAGES_QUERY = """ +UPDATE {table} SET status = 'pending' +WHERE status = 'processing' + AND COALESCE(claimed_at, created_at) < now() - make_interval(secs => $1) + AND attempts < $2 +""" + +FAIL_EXHAUSTED_MESSAGES_QUERY = """ +UPDATE {table} SET status = 'failed' +WHERE status = 'processing' + AND COALESCE(claimed_at, created_at) < now() - make_interval(secs => $1) + AND attempts >= $2 +RETURNING id, task_id, task_name, attempts +""" diff --git a/src/taskiq_pg/psqlpy/broker.py b/src/taskiq_pg/psqlpy/broker.py index a82d28d..724c06b 100644 --- a/src/taskiq_pg/psqlpy/broker.py +++ b/src/taskiq_pg/psqlpy/broker.py @@ -40,6 +40,8 @@ class MessageRow: labels: JSONB status: str created_at: datetime + claimed_at: datetime | None = None + attempts: int = 0 class PSQLPyBroker(BasePostgresBroker): @@ -65,6 +67,7 @@ def __init__( # noqa: PLR0913 listen_keepalive_interval: float | None = 30.0, listen_keepalive_timeout: float = 5.0, poll_interval: float = 5.0, + processing_timeout: float | None = None, ) -> None: """ Construct a new PSQLPyBroker. @@ -84,6 +87,8 @@ def __init__( # noqa: PLR0913 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. + processing_timeout: Seconds after which an unacknowledged claimed message is delivered again + (at-least-once delivery); None keeps at-most-once delivery. """ super().__init__( dsn=dsn, @@ -96,6 +101,7 @@ def __init__( # noqa: PLR0913 listen_keepalive_interval=listen_keepalive_interval, listen_keepalive_timeout=listen_keepalive_timeout, poll_interval=poll_interval, + processing_timeout=processing_timeout, ) self._owns_write_pool = True diff --git a/src/taskiq_pg/psycopg/broker.py b/src/taskiq_pg/psycopg/broker.py index 29f6dc7..2faa3f7 100644 --- a/src/taskiq_pg/psycopg/broker.py +++ b/src/taskiq_pg/psycopg/broker.py @@ -62,6 +62,7 @@ def __init__( listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., poll_interval: float = ..., + processing_timeout: float | None = ..., ) -> None: ... @tp.overload @@ -81,6 +82,7 @@ def __init__( listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., poll_interval: float = ..., + processing_timeout: float | None = ..., ) -> None: ... @tp.overload @@ -100,6 +102,7 @@ def __init__( listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., poll_interval: float = ..., + processing_timeout: float | None = ..., ) -> None: ... @tp.overload @@ -119,6 +122,7 @@ def __init__( listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., poll_interval: float = ..., + processing_timeout: float | None = ..., ) -> None: ... def __init__( # noqa: PLR0913 @@ -137,6 +141,7 @@ def __init__( # noqa: PLR0913 listen_keepalive_interval: float | None = 30.0, listen_keepalive_timeout: float = 5.0, poll_interval: float = 5.0, + processing_timeout: float | None = None, ) -> None: """ Construct a new PsycopgBroker. @@ -157,6 +162,8 @@ def __init__( # noqa: PLR0913 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. + processing_timeout: Seconds after which an unacknowledged claimed message is delivered again + (at-least-once delivery); None keeps at-most-once delivery. """ super().__init__( dsn=dsn, @@ -170,6 +177,7 @@ def __init__( # noqa: PLR0913 listen_keepalive_interval=listen_keepalive_interval, listen_keepalive_timeout=listen_keepalive_timeout, poll_interval=poll_interval, + processing_timeout=processing_timeout, ) self._owns_write_pool = True diff --git a/tests/integration/test_processing_timeout.py b/tests/integration/test_processing_timeout.py new file mode 100644 index 0000000..387073f --- /dev/null +++ b/tests/integration/test_processing_timeout.py @@ -0,0 +1,193 @@ +import asyncio +import typing as tp + +import asyncpg +import pytest +from taskiq import AckableMessage + +from tests.integration.test_polling import insert_pending, unique_names + +from taskiq_pg.asyncpg import AsyncpgBroker + + +Broker: tp.TypeAlias = AsyncpgBroker +BROKERS: list[tp.Any] = [AsyncpgBroker] + +FAST_POLL: dict[str, float] = {"poll_interval": 0.2} + + +async def next_message(listener: tp.AsyncIterator[AckableMessage], timeout: float) -> AckableMessage: + return await asyncio.wait_for(anext(listener), timeout) + + +async def status_of(connection: asyncpg.Connection, table: str, data: str) -> str | None: + return tp.cast( + "str | None", + await connection.fetchval(f"SELECT status FROM {table} WHERE message = $1", data), # noqa: S608 + ) + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", BROKERS) +async def test_when_claimed_message_is_not_acknowledged__then_it_is_delivered_again_after_processing_timeout( + pg_dsn: str, + connection: asyncpg.Connection, + broker_class: type[Broker], +) -> None: + # given + names = unique_names() + broker = broker_class(dsn=pg_dsn, processing_timeout=0.5, **FAST_POLL, **names) + await broker.startup() + listener = broker.listen() + try: + await insert_pending(connection, names["table_name"], '{"n":1}', {}) + first = await next_message(listener, timeout=3) + + # when: the worker "dies" without acknowledging the message + second = await next_message(listener, timeout=5) + + # then + assert first.data == second.data == b'{"n":1}' + finally: + await listener.aclose() + await broker.shutdown() + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", BROKERS) +async def test_when_processing_timeout_is_not_set__then_claimed_message_is_not_delivered_again( + pg_dsn: str, + connection: asyncpg.Connection, + broker_class: type[Broker], +) -> None: + # given + names = unique_names() + broker = broker_class(dsn=pg_dsn, **FAST_POLL, **names) + await broker.startup() + listener = broker.listen() + pending: asyncio.Task[AckableMessage] | None = None + try: + await insert_pending(connection, names["table_name"], '{"n":1}', {}) + await next_message(listener, timeout=3) + + # when + pending = asyncio.create_task(next_message(listener, timeout=1.5)) + await asyncio.gather(pending, return_exceptions=True) + + # then + assert isinstance(pending.exception(), TimeoutError), "At-most-once: the message must not come back" + assert await status_of(connection, names["table_name"], '{"n":1}') == "processing" + finally: + await listener.aclose() + await broker.shutdown() + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", BROKERS) +async def test_when_attempts_are_exhausted__then_message_is_marked_as_failed( + pg_dsn: str, + connection: asyncpg.Connection, + broker_class: type[Broker], + caplog: pytest.LogCaptureFixture, +) -> None: + # given + names = unique_names() + broker = broker_class(dsn=pg_dsn, processing_timeout=0.3, max_retry_attempts=2, **FAST_POLL, **names) + await broker.startup() + listener = broker.listen() + try: + await insert_pending(connection, names["table_name"], '{"n":1}', {}) + await next_message(listener, timeout=3) + await next_message(listener, timeout=5) + + # when + with caplog.at_level("WARNING"): + third = asyncio.create_task(next_message(listener, timeout=1.5)) + await asyncio.gather(third, return_exceptions=True) + + # then + assert isinstance(third.exception(), TimeoutError), "No delivery beyond max_retry_attempts" + assert await status_of(connection, names["table_name"], '{"n":1}') == "failed" + assert "marked as failed" in caplog.text + finally: + await listener.aclose() + await broker.shutdown() + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", BROKERS) +async def test_when_message_is_acknowledged__then_it_is_not_delivered_again( + pg_dsn: str, + connection: asyncpg.Connection, + broker_class: type[Broker], +) -> None: + # given + names = unique_names() + broker = broker_class(dsn=pg_dsn, processing_timeout=0.3, **FAST_POLL, **names) + await broker.startup() + listener = broker.listen() + try: + await insert_pending(connection, names["table_name"], '{"n":1}', {}) + message = await next_message(listener, timeout=3) + + # when + acknowledgement = message.ack() + assert acknowledgement is not None + await acknowledgement + again = asyncio.create_task(next_message(listener, timeout=1.2)) + await asyncio.gather(again, return_exceptions=True) + + # then + assert isinstance(again.exception(), TimeoutError) + assert await status_of(connection, names["table_name"], '{"n":1}') is None + finally: + await listener.aclose() + await broker.shutdown() + + +OLD_SCHEMA = """ +CREATE TABLE {} ( + id SERIAL PRIMARY KEY, + task_id VARCHAR NOT NULL, + task_name VARCHAR NOT NULL, + message TEXT NOT NULL, + labels JSONB NOT NULL, + status TEXT NOT NULL DEFAULT 'pending', + created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +) +""" + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", BROKERS) +async def test_when_table_has_the_old_schema__then_it_is_migrated_and_stuck_messages_are_delivered( + pg_dsn: str, + connection: asyncpg.Connection, + broker_class: type[Broker], +) -> None: + # given: a table from an older version with a message stuck in 'processing' for an hour + names = unique_names() + table = names["table_name"] + await connection.execute(OLD_SCHEMA.format(table)) + await connection.execute( + f"INSERT INTO {table} (task_id, task_name, message, labels, status, created_at)" # noqa: S608 + " VALUES ('old', 'example:old', '{\"old\":true}', '{}', 'processing', now() - interval '1 hour')", + ) + broker = broker_class(dsn=pg_dsn, processing_timeout=60, **FAST_POLL, **names) + + # when + await broker.startup() + listener = broker.listen() + try: + message = await next_message(listener, timeout=3) + + # then + assert message.data == b'{"old":true}' + columns = await connection.fetch( + "SELECT column_name FROM information_schema.columns WHERE table_name = $1", + table, + ) + assert {"claimed_at", "attempts"} <= {row["column_name"] for row in columns} + finally: + await listener.aclose() + await broker.shutdown() diff --git a/tests/unit/test_listen_keepalive_params.py b/tests/unit/test_listen_keepalive_params.py index 11f7c76..10ab91f 100644 --- a/tests/unit/test_listen_keepalive_params.py +++ b/tests/unit/test_listen_keepalive_params.py @@ -69,3 +69,33 @@ def test_when_poll_interval_is_not_positive__then_error_is_raised(broker_class: # when / then with pytest.raises(ValueError, match="poll_interval"): broker_class(poll_interval=poll_interval) + + +@pytest.mark.unit +@pytest.mark.parametrize("broker_class", BROKERS) +def test_when_broker_is_created__then_delivery_is_at_most_once_by_default(broker_class: tp.Any) -> None: + # when + broker = broker_class() + + # then + assert broker.processing_timeout is None + + +@pytest.mark.unit +@pytest.mark.parametrize("broker_class", BROKERS) +@pytest.mark.parametrize( + ("kwargs", "match"), + [ + ({"processing_timeout": 0}, "processing_timeout"), + ({"processing_timeout": -1}, "processing_timeout"), + ({"max_retry_attempts": 0}, "max_retry_attempts"), + ], +) +def test_when_delivery_settings_are_invalid__then_error_is_raised( + broker_class: tp.Any, + kwargs: dict[str, float], + match: str, +) -> None: + # when / then + with pytest.raises(ValueError, match=match): + broker_class(**kwargs) From cbfecb5dabc43debfb1ae76d2573fa69365de72a Mon Sep 17 00:00:00 2001 From: Dmitry Anfimov Date: Wed, 25 Nov 2026 20:06:41 +0100 Subject: [PATCH 2/5] feat(psycopg): optional at-least-once delivery with processing_timeout Same as for asyncpg: claims record claimed_at and attempts, startup adds the columns, and with processing_timeout set each poll returns stale claimed messages to the queue or marks exhausted ones as failed. A database error while doing so is logged and retried on the next poll. --- src/taskiq_pg/psycopg/broker.py | 40 ++++++++++++++++++++ src/taskiq_pg/psycopg/queries.py | 31 ++++++++++++++- tests/integration/test_processing_timeout.py | 5 ++- 3 files changed, 72 insertions(+), 4 deletions(-) diff --git a/src/taskiq_pg/psycopg/broker.py b/src/taskiq_pg/psycopg/broker.py index 2faa3f7..9655305 100644 --- a/src/taskiq_pg/psycopg/broker.py +++ b/src/taskiq_pg/psycopg/broker.py @@ -14,12 +14,16 @@ from taskiq_pg._internal.retry import retry_delays from taskiq_pg._internal.tasks import cancel_and_wait from taskiq_pg.psycopg.queries import ( + ADD_DELIVERY_COLUMNS_QUERY, CLAIM_MESSAGE_QUERY, CLAIM_NEXT_READY_MESSAGE_QUERY, CREATE_MESSAGE_TABLE_QUERY, CREATE_PENDING_INDEX_QUERY, + CREATE_PROCESSING_INDEX_QUERY, DELETE_MESSAGE_QUERY, + FAIL_EXHAUSTED_MESSAGES_QUERY, INSERT_MESSAGE_QUERY, + RELEASE_STALE_MESSAGES_QUERY, ) @@ -214,12 +218,20 @@ async def startup(self) -> None: ): 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(ADD_DELIVERY_COLUMNS_QUERY).format(table=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.processing_timeout is not None: + await cursor.execute( + sql.SQL(CREATE_PROCESSING_INDEX_QUERY).format( + index=sql.Identifier(f"{self.table_name}_processing_idx"), + table=sql.Identifier(self.table_name), + ), + ) if self._owns_read_conn: await self._connect_listener() @@ -435,6 +447,7 @@ async def listen(self) -> AsyncGenerator[AckableMessage, None]: """ async for payload in self._listen_context(): if payload == POLL_NOW: + await self._release_stale_messages() while (claimed := await self._claim_next_ready()) is not None: yield self._ackable(claimed) continue @@ -466,6 +479,33 @@ async def _claim_next_ready(self) -> tuple[tp.Any, ...] | None: logger.warning("Polling for pending messages failed; will retry", exc_info=True) return None + async def _release_stale_messages(self) -> None: + """ + With processing_timeout set, return messages claimed too long ago to the queue. + + A message whose attempts are exhausted is marked as failed instead. + """ + if self.processing_timeout is None: + return + table = sql.Identifier(self.table_name) + params = [self.processing_timeout, self.max_retry_attempts] + try: + async with self._write_pool.connection() as connection, connection.cursor() as cursor: + await cursor.execute(sql.SQL(RELEASE_STALE_MESSAGES_QUERY).format(table=table), params) + await cursor.execute(sql.SQL(FAIL_EXHAUSTED_MESSAGES_QUERY).format(table=table), params) + failed = await cursor.fetchall() + except psycopg.OperationalError: + logger.warning("Releasing stale messages failed; will retry", exc_info=True) + return + for message_id, task_id, task_name, attempts in failed: + logger.warning( + "Message %s (task %s, %s) was not acknowledged after %s attempts; marked as failed", + message_id, + task_id, + task_name, + attempts, + ) + def _ackable(self, claimed: tuple[tp.Any, ...]) -> AckableMessage: """Wrap a claimed message; acknowledging it deletes the row.""" message_id = int(claimed[0]) diff --git a/src/taskiq_pg/psycopg/queries.py b/src/taskiq_pg/psycopg/queries.py index a4bfaeb..928614b 100644 --- a/src/taskiq_pg/psycopg/queries.py +++ b/src/taskiq_pg/psycopg/queries.py @@ -64,7 +64,11 @@ RETURNING id """ -CLAIM_MESSAGE_QUERY = "UPDATE {} SET status = 'processing' WHERE id = %s AND status = 'pending' RETURNING *" +CLAIM_MESSAGE_QUERY = """ +UPDATE {} SET status = 'processing', claimed_at = now(), attempts = attempts + 1 +WHERE id = %s AND status = 'pending' +RETURNING * +""" DELETE_MESSAGE_QUERY = "DELETE FROM {} WHERE id = %s" @@ -103,7 +107,7 @@ 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' +UPDATE {table} SET status = 'processing', claimed_at = now(), attempts = attempts + 1 WHERE id = ( SELECT id FROM {table} WHERE status = 'pending' @@ -119,3 +123,26 @@ ) RETURNING * """ + +ADD_DELIVERY_COLUMNS_QUERY = """ +ALTER TABLE {table} + ADD COLUMN IF NOT EXISTS claimed_at TIMESTAMP WITH TIME ZONE, + ADD COLUMN IF NOT EXISTS attempts INTEGER NOT NULL DEFAULT 0 +""" + +CREATE_PROCESSING_INDEX_QUERY = "CREATE INDEX IF NOT EXISTS {index} ON {table} (claimed_at) WHERE status = 'processing'" + +RELEASE_STALE_MESSAGES_QUERY = """ +UPDATE {table} SET status = 'pending' +WHERE status = 'processing' + AND COALESCE(claimed_at, created_at) < now() - make_interval(secs => %s) + AND attempts < %s +""" + +FAIL_EXHAUSTED_MESSAGES_QUERY = """ +UPDATE {table} SET status = 'failed' +WHERE status = 'processing' + AND COALESCE(claimed_at, created_at) < now() - make_interval(secs => %s) + AND attempts >= %s +RETURNING id, task_id, task_name, attempts +""" diff --git a/tests/integration/test_processing_timeout.py b/tests/integration/test_processing_timeout.py index 387073f..6ade00e 100644 --- a/tests/integration/test_processing_timeout.py +++ b/tests/integration/test_processing_timeout.py @@ -8,10 +8,11 @@ from tests.integration.test_polling import insert_pending, unique_names 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] FAST_POLL: dict[str, float] = {"poll_interval": 0.2} From 42e76622d2238ef9bf80e761f39a524089375bb5 Mon Sep 17 00:00:00 2001 From: Dmitry Anfimov Date: Wed, 25 Nov 2026 20:09:02 +0100 Subject: [PATCH 3/5] feat(psqlpy): optional at-least-once delivery with processing_timeout Same as for asyncpg: claims record claimed_at and attempts, startup adds the columns, and with processing_timeout set each poll returns stale claimed messages to the queue or marks exhausted ones as failed. --- src/taskiq_pg/psqlpy/broker.py | 34 ++++++++++++++++++++ src/taskiq_pg/psqlpy/queries.py | 31 ++++++++++++++++-- tests/integration/test_processing_timeout.py | 5 +-- 3 files changed, 66 insertions(+), 4 deletions(-) diff --git a/src/taskiq_pg/psqlpy/broker.py b/src/taskiq_pg/psqlpy/broker.py index 724c06b..eaa3187 100644 --- a/src/taskiq_pg/psqlpy/broker.py +++ b/src/taskiq_pg/psqlpy/broker.py @@ -15,12 +15,16 @@ 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 ( + ADD_DELIVERY_COLUMNS_QUERY, CLAIM_MESSAGE_QUERY, CLAIM_NEXT_READY_MESSAGE_QUERY, CREATE_MESSAGE_TABLE_QUERY, CREATE_PENDING_INDEX_QUERY, + CREATE_PROCESSING_INDEX_QUERY, DELETE_MESSAGE_QUERY, + FAIL_EXHAUSTED_MESSAGES_QUERY, INSERT_MESSAGE_QUERY, + RELEASE_STALE_MESSAGES_QUERY, ) @@ -123,9 +127,17 @@ async def startup(self) -> None: 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(ADD_DELIVERY_COLUMNS_QUERY.format(table=self.table_name)) await transaction.execute( CREATE_PENDING_INDEX_QUERY.format(index=f"{self.table_name}_pending_idx", table=self.table_name), ) + if self.processing_timeout is not None: + await transaction.execute( + CREATE_PROCESSING_INDEX_QUERY.format( + index=f"{self.table_name}_processing_idx", + table=self.table_name, + ), + ) self._queue = asyncio.Queue() @@ -302,6 +314,7 @@ async def listen(self) -> AsyncGenerator[AckableMessage, None]: try: if loop.time() >= next_poll: next_poll = loop.time() + self.poll_interval + await self._release_stale_messages() while (claimed := await self._claim_next_ready()) is not None: yield self._ackable(claimed) continue @@ -335,6 +348,27 @@ async def _claim_next_ready(self) -> MessageRow | None: rows = tp.cast("list[MessageRow]", result.as_class(MessageRow)) return rows[0] if rows else None + async def _release_stale_messages(self) -> None: + """ + With processing_timeout set, return messages claimed too long ago to the queue. + + A message whose attempts are exhausted is marked as failed instead. + """ + if self.processing_timeout is None: + return + params = [self.processing_timeout, self.max_retry_attempts] + async with self._write_pool.acquire() as conn: + await conn.execute(RELEASE_STALE_MESSAGES_QUERY.format(table=self.table_name), params) + failed = await conn.fetch(FAIL_EXHAUSTED_MESSAGES_QUERY.format(table=self.table_name), params) + for row in failed.result(): + logger.warning( + "Message %s (task %s, %s) was not acknowledged after %s attempts; marked as failed", + row["id"], + row["task_id"], + row["task_name"], + row["attempts"], + ) + def _ackable(self, claimed: MessageRow) -> AckableMessage: """Wrap a claimed message; acknowledging it deletes the row.""" message_id = claimed.id diff --git a/src/taskiq_pg/psqlpy/queries.py b/src/taskiq_pg/psqlpy/queries.py index 87bcf11..150cf76 100644 --- a/src/taskiq_pg/psqlpy/queries.py +++ b/src/taskiq_pg/psqlpy/queries.py @@ -64,7 +64,11 @@ RETURNING id """ -CLAIM_MESSAGE_QUERY = "UPDATE {} SET status = 'processing' WHERE id = $1 AND status = 'pending' RETURNING *" +CLAIM_MESSAGE_QUERY = """ +UPDATE {} SET status = 'processing', claimed_at = now(), attempts = attempts + 1 +WHERE id = $1 AND status = 'pending' +RETURNING * +""" DELETE_MESSAGE_QUERY = "DELETE FROM {} WHERE id = $1" @@ -103,7 +107,7 @@ 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' +UPDATE {table} SET status = 'processing', claimed_at = now(), attempts = attempts + 1 WHERE id = ( SELECT id FROM {table} WHERE status = 'pending' @@ -119,3 +123,26 @@ ) RETURNING * """ + +ADD_DELIVERY_COLUMNS_QUERY = """ +ALTER TABLE {table} + ADD COLUMN IF NOT EXISTS claimed_at TIMESTAMP WITH TIME ZONE, + ADD COLUMN IF NOT EXISTS attempts INTEGER NOT NULL DEFAULT 0 +""" + +CREATE_PROCESSING_INDEX_QUERY = "CREATE INDEX IF NOT EXISTS {index} ON {table} (claimed_at) WHERE status = 'processing'" + +RELEASE_STALE_MESSAGES_QUERY = """ +UPDATE {table} SET status = 'pending' +WHERE status = 'processing' + AND COALESCE(claimed_at, created_at) < now() - make_interval(secs => $1) + AND attempts < $2 +""" + +FAIL_EXHAUSTED_MESSAGES_QUERY = """ +UPDATE {table} SET status = 'failed' +WHERE status = 'processing' + AND COALESCE(claimed_at, created_at) < now() - make_interval(secs => $1) + AND attempts >= $2 +RETURNING id, task_id, task_name, attempts +""" diff --git a/tests/integration/test_processing_timeout.py b/tests/integration/test_processing_timeout.py index 6ade00e..e2340d5 100644 --- a/tests/integration/test_processing_timeout.py +++ b/tests/integration/test_processing_timeout.py @@ -8,11 +8,12 @@ from tests.integration.test_polling import insert_pending, unique_names 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] FAST_POLL: dict[str, float] = {"poll_interval": 0.2} From 5e8cbc89f4bba31fdbe2315413c2bce4a8a0b7a0 Mon Sep 17 00:00:00 2001 From: Dmitry Anfimov Date: Wed, 25 Nov 2026 20:11:19 +0100 Subject: [PATCH 4/5] feat(aiopg): optional at-least-once delivery with processing_timeout Same as for asyncpg: claims record claimed_at and attempts, startup adds the columns, and with processing_timeout set each poll returns stale claimed messages to the queue or marks exhausted ones as failed. --- src/taskiq_pg/aiopg/broker.py | 35 ++++++++++++++++++++ src/taskiq_pg/aiopg/queries.py | 31 +++++++++++++++-- tests/integration/test_processing_timeout.py | 5 +-- 3 files changed, 67 insertions(+), 4 deletions(-) diff --git a/src/taskiq_pg/aiopg/broker.py b/src/taskiq_pg/aiopg/broker.py index ccd7110..c05901a 100644 --- a/src/taskiq_pg/aiopg/broker.py +++ b/src/taskiq_pg/aiopg/broker.py @@ -11,12 +11,16 @@ 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 ( + ADD_DELIVERY_COLUMNS_QUERY, CLAIM_MESSAGE_QUERY, CLAIM_NEXT_READY_MESSAGE_QUERY, CREATE_MESSAGE_TABLE_QUERY, CREATE_PENDING_INDEX_QUERY, + CREATE_PROCESSING_INDEX_QUERY, DELETE_MESSAGE_QUERY, + FAIL_EXHAUSTED_MESSAGES_QUERY, INSERT_MESSAGE_QUERY, + RELEASE_STALE_MESSAGES_QUERY, ) @@ -194,9 +198,17 @@ async def startup(self) -> None: try: await cursor.execute(schema_lock_query(self.table_name)) await cursor.execute(CREATE_MESSAGE_TABLE_QUERY.format(self.table_name)) + await cursor.execute(ADD_DELIVERY_COLUMNS_QUERY.format(table=self.table_name)) await cursor.execute( CREATE_PENDING_INDEX_QUERY.format(index=f"{self.table_name}_pending_idx", table=self.table_name), ) + if self.processing_timeout is not None: + await cursor.execute( + CREATE_PROCESSING_INDEX_QUERY.format( + index=f"{self.table_name}_processing_idx", + table=self.table_name, + ), + ) except BaseException: await cursor.execute("ROLLBACK") raise @@ -370,6 +382,7 @@ async def listen(self) -> AsyncGenerator[AckableMessage, None]: try: if loop.time() >= next_poll: next_poll = loop.time() + self.poll_interval + await self._release_stale_messages() while ( claimed := await self._claim(CLAIM_NEXT_READY_MESSAGE_QUERY.format(table=self.table_name)) ) is not None: @@ -398,6 +411,28 @@ async def _claim(self, query: str, params: tuple[tp.Any, ...] = ()) -> tuple[tp. await cursor.execute(query, params) return tp.cast("tuple[tp.Any, ...] | None", await cursor.fetchone()) + async def _release_stale_messages(self) -> None: + """ + With processing_timeout set, return messages claimed too long ago to the queue. + + A message whose attempts are exhausted is marked as failed instead. + """ + if self.processing_timeout is None or self._write_pool is None: + return + params = (self.processing_timeout, self.max_retry_attempts) + async with self._write_pool.acquire() as conn, conn.cursor() as cursor: + await cursor.execute(RELEASE_STALE_MESSAGES_QUERY.format(table=self.table_name), params) + await cursor.execute(FAIL_EXHAUSTED_MESSAGES_QUERY.format(table=self.table_name), params) + failed = await cursor.fetchall() + for message_id, task_id, task_name, attempts in failed: + logger.warning( + "Message %s (task %s, %s) was not acknowledged after %s attempts; marked as failed", + message_id, + task_id, + task_name, + attempts, + ) + def _ackable(self, claimed: tuple[tp.Any, ...]) -> AckableMessage: """Wrap a claimed message; acknowledging it deletes the row.""" message_id = int(claimed[0]) diff --git a/src/taskiq_pg/aiopg/queries.py b/src/taskiq_pg/aiopg/queries.py index 7112254..2523582 100644 --- a/src/taskiq_pg/aiopg/queries.py +++ b/src/taskiq_pg/aiopg/queries.py @@ -96,14 +96,18 @@ RETURNING id """ -CLAIM_MESSAGE_QUERY = "UPDATE {} SET status = 'processing' WHERE id = %s AND status = 'pending' RETURNING id, message" +CLAIM_MESSAGE_QUERY = """ +UPDATE {} SET status = 'processing', claimed_at = now(), attempts = attempts + 1 +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' +UPDATE {table} SET status = 'processing', claimed_at = now(), attempts = attempts + 1 WHERE id = ( SELECT id FROM {table} WHERE status = 'pending' @@ -119,3 +123,26 @@ ) RETURNING id, message """ + +ADD_DELIVERY_COLUMNS_QUERY = """ +ALTER TABLE {table} + ADD COLUMN IF NOT EXISTS claimed_at TIMESTAMP WITH TIME ZONE, + ADD COLUMN IF NOT EXISTS attempts INTEGER NOT NULL DEFAULT 0 +""" + +CREATE_PROCESSING_INDEX_QUERY = "CREATE INDEX IF NOT EXISTS {index} ON {table} (claimed_at) WHERE status = 'processing'" + +RELEASE_STALE_MESSAGES_QUERY = """ +UPDATE {table} SET status = 'pending' +WHERE status = 'processing' + AND COALESCE(claimed_at, created_at) < now() - make_interval(secs => %s) + AND attempts < %s +""" + +FAIL_EXHAUSTED_MESSAGES_QUERY = """ +UPDATE {table} SET status = 'failed' +WHERE status = 'processing' + AND COALESCE(claimed_at, created_at) < now() - make_interval(secs => %s) + AND attempts >= %s +RETURNING id, task_id, task_name, attempts +""" diff --git a/tests/integration/test_processing_timeout.py b/tests/integration/test_processing_timeout.py index e2340d5..a549cd0 100644 --- a/tests/integration/test_processing_timeout.py +++ b/tests/integration/test_processing_timeout.py @@ -7,13 +7,14 @@ from tests.integration.test_polling import insert_pending, unique_names +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] FAST_POLL: dict[str, float] = {"poll_interval": 0.2} From 92459be7fc0a79939cb544a98aa5402a4886a53b Mon Sep 17 00:00:00 2001 From: Dmitry Anfimov Date: Wed, 25 Nov 2026 23:23:51 +0100 Subject: [PATCH 5/5] fix: do not let an expired claim acknowledge a message claimed again With processing_timeout, a message whose claim expired can be claimed again by another worker. The ack deleted the row by id only, so a slow worker finishing late removed the new claim, and the message was lost if the second worker then died. The ack now deletes the row only while it still has the attempts count of its own claim. Claims return the attempts count; psycopg claims return explicit columns instead of RETURNING *. --- src/taskiq_pg/aiopg/broker.py | 3 +- src/taskiq_pg/aiopg/queries.py | 7 +-- src/taskiq_pg/asyncpg/broker.py | 3 +- src/taskiq_pg/asyncpg/queries.py | 7 +-- src/taskiq_pg/psqlpy/broker.py | 3 +- src/taskiq_pg/psqlpy/queries.py | 3 +- src/taskiq_pg/psycopg/broker.py | 5 +- src/taskiq_pg/psycopg/queries.py | 7 +-- tests/integration/test_processing_timeout.py | 56 ++++++++++++++++++++ 9 files changed, 79 insertions(+), 15 deletions(-) diff --git a/src/taskiq_pg/aiopg/broker.py b/src/taskiq_pg/aiopg/broker.py index c05901a..274981c 100644 --- a/src/taskiq_pg/aiopg/broker.py +++ b/src/taskiq_pg/aiopg/broker.py @@ -437,6 +437,7 @@ 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] + attempts = int(claimed[2]) if not isinstance(message_str, str): msg = "message is not a string" raise TypeError(msg) @@ -446,6 +447,6 @@ async def ack() -> 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,)) + await cursor.execute(DELETE_MESSAGE_QUERY.format(self.table_name), (message_id, attempts)) 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 2523582..c85b425 100644 --- a/src/taskiq_pg/aiopg/queries.py +++ b/src/taskiq_pg/aiopg/queries.py @@ -99,10 +99,11 @@ CLAIM_MESSAGE_QUERY = """ UPDATE {} SET status = 'processing', claimed_at = now(), attempts = attempts + 1 WHERE id = %s AND status = 'pending' -RETURNING id, message +RETURNING id, message, attempts """ -DELETE_MESSAGE_QUERY = "DELETE FROM {} WHERE id = %s" +# Delete only the claim being acknowledged: after processing_timeout another worker may have claimed the row again. +DELETE_MESSAGE_QUERY = "DELETE FROM {} WHERE id = %s AND attempts = %s" CREATE_PENDING_INDEX_QUERY = "CREATE INDEX IF NOT EXISTS {index} ON {table} (id) WHERE status = 'pending'" @@ -121,7 +122,7 @@ LIMIT 1 FOR UPDATE SKIP LOCKED ) -RETURNING id, message +RETURNING id, message, attempts """ ADD_DELIVERY_COLUMNS_QUERY = """ diff --git a/src/taskiq_pg/asyncpg/broker.py b/src/taskiq_pg/asyncpg/broker.py index 295a6d5..5945a79 100644 --- a/src/taskiq_pg/asyncpg/broker.py +++ b/src/taskiq_pg/asyncpg/broker.py @@ -472,12 +472,13 @@ def _ackable(self, claimed: asyncpg.Record) -> AckableMessage: msg = "message is not a string" raise TypeError(msg) message_id = int(claimed["id"]) + attempts = int(claimed["attempts"]) 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) + await conn.execute(DELETE_MESSAGE_QUERY.format(self.table_name), message_id, attempts) 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 0a6fed6..cf985d7 100644 --- a/src/taskiq_pg/asyncpg/queries.py +++ b/src/taskiq_pg/asyncpg/queries.py @@ -67,10 +67,11 @@ CLAIM_MESSAGE_QUERY = """ UPDATE {} SET status = 'processing', claimed_at = now(), attempts = attempts + 1 WHERE id = $1 AND status = 'pending' -RETURNING id, message +RETURNING id, message, attempts """ -DELETE_MESSAGE_QUERY = "DELETE FROM {} WHERE id = $1" +# Delete only the claim being acknowledged: after processing_timeout another worker may have claimed the row again. +DELETE_MESSAGE_QUERY = "DELETE FROM {} WHERE id = $1 AND attempts = $2" CREATE_SCHEDULES_TABLE_QUERY = """ CREATE TABLE IF NOT EXISTS {} ( @@ -121,7 +122,7 @@ LIMIT 1 FOR UPDATE SKIP LOCKED ) -RETURNING id, message +RETURNING id, message, attempts """ ADD_DELIVERY_COLUMNS_QUERY = """ diff --git a/src/taskiq_pg/psqlpy/broker.py b/src/taskiq_pg/psqlpy/broker.py index eaa3187..a615393 100644 --- a/src/taskiq_pg/psqlpy/broker.py +++ b/src/taskiq_pg/psqlpy/broker.py @@ -372,9 +372,10 @@ async def _release_stale_messages(self) -> None: def _ackable(self, claimed: MessageRow) -> AckableMessage: """Wrap a claimed message; acknowledging it deletes the row.""" message_id = claimed.id + attempts = claimed.attempts async def ack() -> None: async with self._write_pool.acquire() as conn: - await conn.execute(DELETE_MESSAGE_QUERY.format(self.table_name), [message_id]) + await conn.execute(DELETE_MESSAGE_QUERY.format(self.table_name), [message_id, attempts]) 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 150cf76..7ae82a0 100644 --- a/src/taskiq_pg/psqlpy/queries.py +++ b/src/taskiq_pg/psqlpy/queries.py @@ -70,7 +70,8 @@ RETURNING * """ -DELETE_MESSAGE_QUERY = "DELETE FROM {} WHERE id = $1" +# Delete only the claim being acknowledged: after processing_timeout another worker may have claimed the row again. +DELETE_MESSAGE_QUERY = "DELETE FROM {} WHERE id = $1 AND attempts = $2" CREATE_SCHEDULES_TABLE_QUERY = """ CREATE TABLE IF NOT EXISTS {} ( diff --git a/src/taskiq_pg/psycopg/broker.py b/src/taskiq_pg/psycopg/broker.py index 9655305..6ae3741 100644 --- a/src/taskiq_pg/psycopg/broker.py +++ b/src/taskiq_pg/psycopg/broker.py @@ -509,7 +509,8 @@ async def _release_stale_messages(self) -> 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] + message_str = claimed[1] + attempts = int(claimed[2]) if not isinstance(message_str, str): msg = "Message is not a string" raise TypeError(msg) @@ -518,7 +519,7 @@ 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], + [message_id, attempts], ) 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 928614b..eae3bd3 100644 --- a/src/taskiq_pg/psycopg/queries.py +++ b/src/taskiq_pg/psycopg/queries.py @@ -67,10 +67,11 @@ CLAIM_MESSAGE_QUERY = """ UPDATE {} SET status = 'processing', claimed_at = now(), attempts = attempts + 1 WHERE id = %s AND status = 'pending' -RETURNING * +RETURNING id, message, attempts """ -DELETE_MESSAGE_QUERY = "DELETE FROM {} WHERE id = %s" +# Delete only the claim being acknowledged: after processing_timeout another worker may have claimed the row again. +DELETE_MESSAGE_QUERY = "DELETE FROM {} WHERE id = %s AND attempts = %s" CREATE_SCHEDULES_TABLE_QUERY = """ CREATE TABLE IF NOT EXISTS {} ( @@ -121,7 +122,7 @@ LIMIT 1 FOR UPDATE SKIP LOCKED ) -RETURNING * +RETURNING id, message, attempts """ ADD_DELIVERY_COLUMNS_QUERY = """ diff --git a/tests/integration/test_processing_timeout.py b/tests/integration/test_processing_timeout.py index a549cd0..2842e40 100644 --- a/tests/integration/test_processing_timeout.py +++ b/tests/integration/test_processing_timeout.py @@ -194,3 +194,59 @@ async def test_when_table_has_the_old_schema__then_it_is_migrated_and_stuck_mess finally: await listener.aclose() await broker.shutdown() + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", BROKERS) +async def test_when_expired_claim_is_acknowledged__then_message_claimed_again_is_kept( + 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, processing_timeout=0.5, **FAST_POLL, **names) + await broker.startup() + listener = broker.listen() + try: + await insert_pending(connection, table, '{"n":1}', {}) + expired = await next_message(listener, timeout=3) + await next_message(listener, timeout=5) # delivered again after processing_timeout + + # when: the slow worker finishes and acknowledges its expired claim + await expired.ack() # type: ignore[misc] + + # then + assert await status_of(connection, table, '{"n":1}') == "processing" + finally: + await listener.aclose() + await broker.shutdown() + + +@pytest.mark.integration +@pytest.mark.parametrize("broker_class", BROKERS) +async def test_when_released_message_is_acknowledged_before_it_is_claimed_again__then_it_is_deleted( + 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, processing_timeout=0.5, **FAST_POLL, **names) + await broker.startup() + listener = broker.listen() + try: + await insert_pending(connection, table, '{"n":1}', {}) + claimed = await next_message(listener, timeout=3) + await connection.execute(f"UPDATE {table} SET status = 'pending', created_at = now() + interval '1 hour'") # noqa: S608 + + # when: the worker finishes after its claim was released, but before the message is claimed again + await claimed.ack() # type: ignore[misc] + + # then + assert await status_of(connection, table, '{"n":1}') is None + finally: + await listener.aclose() + await broker.shutdown()