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..274981c 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, ) @@ -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 AiopgBroker. @@ -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 @@ -186,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 @@ -362,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: @@ -390,10 +411,33 @@ 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]) message_str = claimed[1] + attempts = int(claimed[2]) if not isinstance(message_str, str): msg = "message is not a string" raise TypeError(msg) @@ -403,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 7112254..c85b425 100644 --- a/src/taskiq_pg/aiopg/queries.py +++ b/src/taskiq_pg/aiopg/queries.py @@ -96,14 +96,19 @@ 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, 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'" 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' @@ -117,5 +122,28 @@ LIMIT 1 FOR UPDATE SKIP LOCKED ) -RETURNING id, message +RETURNING id, message, attempts +""" + +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/src/taskiq_pg/asyncpg/broker.py b/src/taskiq_pg/asyncpg/broker.py index 632490d..5945a79 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"] @@ -423,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 ce90015..cf985d7 100644 --- a/src/taskiq_pg/asyncpg/queries.py +++ b/src/taskiq_pg/asyncpg/queries.py @@ -64,9 +64,14 @@ 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, 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 {} ( @@ -103,7 +108,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' @@ -117,5 +122,28 @@ LIMIT 1 FOR UPDATE SKIP LOCKED ) -RETURNING id, message +RETURNING id, message, attempts +""" + +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..a615393 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, ) @@ -40,6 +44,8 @@ class MessageRow: labels: JSONB status: str created_at: datetime + claimed_at: datetime | None = None + attempts: int = 0 class PSQLPyBroker(BasePostgresBroker): @@ -65,6 +71,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 +91,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 +105,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 @@ -117,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() @@ -296,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 @@ -329,12 +348,34 @@ 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 + 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 87bcf11..7ae82a0 100644 --- a/src/taskiq_pg/psqlpy/queries.py +++ b/src/taskiq_pg/psqlpy/queries.py @@ -64,9 +64,14 @@ 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" +# 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 {} ( @@ -103,7 +108,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 +124,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/src/taskiq_pg/psycopg/broker.py b/src/taskiq_pg/psycopg/broker.py index 29f6dc7..6ae3741 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, ) @@ -62,6 +66,7 @@ def __init__( listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., poll_interval: float = ..., + processing_timeout: float | None = ..., ) -> None: ... @tp.overload @@ -81,6 +86,7 @@ def __init__( listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., poll_interval: float = ..., + processing_timeout: float | None = ..., ) -> None: ... @tp.overload @@ -100,6 +106,7 @@ def __init__( listen_keepalive_interval: float | None = ..., listen_keepalive_timeout: float = ..., poll_interval: float = ..., + processing_timeout: float | None = ..., ) -> None: ... @tp.overload @@ -119,6 +126,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 +145,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 +166,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 +181,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 @@ -206,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() @@ -427,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 @@ -458,10 +479,38 @@ 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]) - 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) @@ -470,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 a4bfaeb..eae3bd3 100644 --- a/src/taskiq_pg/psycopg/queries.py +++ b/src/taskiq_pg/psycopg/queries.py @@ -64,9 +64,14 @@ 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 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 {} ( @@ -103,7 +108,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' @@ -117,5 +122,28 @@ LIMIT 1 FOR UPDATE SKIP LOCKED ) -RETURNING * +RETURNING id, message, attempts +""" + +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 new file mode 100644 index 0000000..2842e40 --- /dev/null +++ b/tests/integration/test_processing_timeout.py @@ -0,0 +1,252 @@ +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.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 | AiopgBroker +BROKERS: list[tp.Any] = [AsyncpgBroker, PsycopgBroker, PSQLPyBroker, AiopgBroker] + +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() + + +@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() 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)