acemq_amqp.patterns.replay

Putting dead letters back, when the thing that killed them is fixed.

This is the pattern somebody actually needs at three in the morning: a dead-letter queue has two thousand messages in it, the bug is fixed, and they have to go back through — but not all of them, not silently, and not in a way that cannot be stopped half way.

So a replay takes a filter, a limit and a deadline, and reports what it did and why it stopped. "Moved 500" means something quite different when the limit was 500, which is why the reason comes back with the count.

  1# Copyright 2026 AceMQ.
  2#
  3# Licensed under the Apache License, Version 2.0 (the "License");
  4# you may not use this file except in compliance with the License.
  5# You may obtain a copy of the License at
  6#
  7#     https://www.apache.org/licenses/LICENSE-2.0
  8#
  9# Unless required by applicable law or agreed to in writing, software
 10# distributed under the License is distributed on an "AS IS" BASIS,
 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 12# See the License for the specific language governing permissions and
 13# limitations under the License.
 14
 15"""Putting dead letters back, when the thing that killed them is fixed.
 16
 17This is the pattern somebody actually needs at three in the morning: a
 18dead-letter queue has two thousand messages in it, the bug is fixed, and they
 19have to go back through — but not all of them, not silently, and not in a way
 20that cannot be stopped half way.
 21
 22So a replay takes a filter, a limit and a deadline, and reports what it did and
 23why it stopped. "Moved 500" means something quite different when the limit was
 24500, which is why the reason comes back with the count.
 25"""
 26
 27from __future__ import annotations
 28
 29import asyncio
 30import logging
 31from collections.abc import Callable
 32from dataclasses import dataclass
 33from datetime import datetime, timedelta, timezone
 34from typing import Any, TypeAlias
 35
 36from ..connection import Connection
 37from ..envelope import Envelope
 38from ..errors import AceMQError, PublishError
 39from ..transport import Delivery, Outbound
 40
 41log = logging.getLogger("acemq")
 42
 43#: The queue a message was replayed out of.
 44HEADER_REPLAYED_FROM = "acemq-replayed-from"
 45
 46#: When it was replayed, as ISO-8601 UTC with milliseconds and a ``Z``:
 47#: ``2026-02-03T04:05:06.789Z`` (AceMQ TCK requirement AMQP-ENV-013).
 48HEADER_REPLAYED_AT = "acemq-replayed-at"
 49
 50#: How many times it has been replayed, from 1.
 51HEADER_REPLAY_COUNT = "acemq-replay-count"
 52
 53#: Decides whether a message goes back. Returning ``False`` leaves it where it
 54#: is, which is what makes a replay something that can be done in stages.
 55ReplayFilter: TypeAlias = Callable[[Envelope, bytes], bool]
 56
 57
 58@dataclass(frozen=True, slots=True)
 59class ReplayResult:
 60    """What a replay did, and why it stopped.
 61
 62    :param moved: how many messages were republished
 63    :param skipped: how many the filter declined, and so left where they were
 64    :param reason: ``drained``, ``limit`` or ``deadline``
 65    """
 66
 67    moved: int
 68    skipped: int
 69    reason: str
 70
 71    def __str__(self) -> str:
 72        return f"moved {self.moved}, skipped {self.skipped} ({self.reason})"
 73
 74
 75class ReplayError(AceMQError):
 76    """A replay stopped because something failed.
 77
 78    It carries the :class:`ReplayResult` it had reached, because "it failed" and
 79    "it failed after moving four hundred" are different things to be told at
 80    three in the morning.
 81    """
 82
 83    def __init__(self, result: ReplayResult, what: str) -> None:
 84        self.result = result
 85        super().__init__(f"acemq: {what} (after {result})")
 86
 87
 88async def replay(
 89    connection: Connection,
 90    queue: str,
 91    *,
 92    exchange: str = "",
 93    routing_key: str | None = None,
 94    limit: int = 0,
 95    deadline: timedelta | None = None,
 96    only: ReplayFilter | None = None,
 97    restart: bool = True,
 98    return_wait: timedelta = timedelta(seconds=10),
 99) -> ReplayResult:
100    """Moves messages from a queue back onto an exchange::
101
102        result = await replay(
103            mq,
104            dead_letter_queue("orders.new"),
105            limit=500,
106            only=lambda envelope, body: "timeout" in envelope.error,
107        )
108        print(result)   # moved 137, skipped 363 (drained)
109
110    Each message is stamped with :data:`HEADER_REPLAYED_FROM`,
111    :data:`HEADER_REPLAYED_AT` and :data:`HEADER_REPLAY_COUNT`, so a consumer
112    that needs to treat a replayed message differently can, and one that does
113    not is unaffected.
114
115    :param connection: where to read from and publish to
116    :param queue: where the messages are now, usually a dead-letter queue
117    :param exchange: where they go back to, empty to publish to a queue by name
118    :param routing_key: what to publish them under. ``None`` keeps each
119        message's own, so a message goes back where it came from rather than
120        everywhere
121    :param limit: stop after this many. Zero means no limit, which against a
122        queue something is still writing to may mean it does not stop at all —
123        prefer a limit
124    :param deadline: stop after this long. ``None`` means no deadline
125    :param only: which messages to move. ``None`` moves all of them
126    :param restart: give each message a fresh set of attempts, clearing the
127        counter and the error that dead-lettered it. On by default because it is
128        what a replay is for: a message that arrives back on attempt five of a
129        five-attempt policy is dead-lettered again before a handler sees it, and
130        the operator who has just fixed the bug has moved two thousand messages
131        from one queue to the same queue. Turn it off to put back exactly what
132        was there — for an audit, or for a queue read by something that counts
133        attempts itself
134    :param return_wait: how long, once the pass is over, to wait for the
135        messages ``only`` passed over to show on the queue again. Ten seconds by
136        default. They are held unacknowledged for the whole pass, and the wait
137        reads the queue's depth, so a consumer draining the same queue at the
138        same time can make it run out; it then logs a warning and returns, and
139        the messages are still on the queue. Zero does not wait at all
140    :returns: what it did and why it stopped
141    :raises ReplayError: when reading or republishing failed. Whatever had
142        already been moved has been moved; the rest is still on the queue
143    """
144    if not queue:
145        raise ValueError("acemq: a replay needs a queue to read from")
146    if return_wait < timedelta(0):
147        raise ValueError("acemq: a replay's return_wait cannot be negative")
148
149    clock = asyncio.get_running_loop()
150    expires = None if deadline is None else clock.time() + deadline.total_seconds()
151    moved = 0
152    skipped = 0
153
154    # Messages the filter declines are held unsettled until the pass is over
155    # rather than returned one at a time. Returning one immediately does not
156    # work: the broker puts it back where it was, at the head of the queue, so
157    # the next pull hands over the same message and nothing behind it is ever
158    # looked at. Holding them takes them out of the way for the length of the
159    # pass, and because the broker is the one holding them, a crash returns them
160    # rather than losing them.
161    declined: list[Delivery] = []
162
163    try:
164        while True:
165            if limit > 0 and moved >= limit:
166                return ReplayResult(moved, skipped, "limit")
167            if expires is not None and clock.time() >= expires:
168                return ReplayResult(moved, skipped, "deadline")
169
170            try:
171                message = await connection.pull(queue)
172            except Exception as failure:
173                raise ReplayError(
174                    ReplayResult(moved, skipped, "failed"),
175                    f"cannot read {queue!r} to replay it: {failure}",
176                ) from failure
177
178            if message is None:
179                # Everything available has been offered. What is left is what
180                # this pass declined, and it goes back as the pass ends.
181                return ReplayResult(moved, skipped, "drained")
182
183            envelope = Envelope.from_headers(
184                message.headers, message.routing_key, message.message_id
185            )
186            if only is not None and not only(envelope, message.body):
187                skipped += 1
188                declined.append(message)
189                continue
190
191            try:
192                await _move(
193                    connection, message, envelope, queue, exchange, routing_key, restart
194                )
195            except Exception as failure:
196                raise ReplayError(
197                    ReplayResult(moved, skipped, "failed"),
198                    f"cannot republish a message from {queue!r}: {failure}",
199                ) from failure
200            moved += 1
201    finally:
202        await _return_declined(connection, queue, declined, return_wait.total_seconds())
203
204
205async def _return_declined(
206    connection: Connection, queue: str, declined: list[Delivery], wait: float
207) -> None:
208    """Returns what the pass declined, and waits until the queue shows them.
209
210    A requeue is fire-and-forget in AMQP: ``basic.nack`` has no reply, and a
211    quorum queue takes it through its log before the message counts as ready
212    again. Returning as soon as the nacks are written let a caller read the
213    queue's depth straight after a replay and be told 0 for a queue holding
214    every message the filter passed over. So the depth is read before the
215    messages go back, and the replay ends once it has grown by that many.
216    """
217    if not declined:
218        return
219    try:
220        before: int | None = await connection.message_count(queue)
221    except Exception:
222        before = None
223    for held in declined:
224        # Nothing to report if this fails: the pass is over, and a message
225        # that cannot be returned is one the broker returns itself when this
226        # connection goes.
227        await _return_quietly(held)
228    if before is None or wait <= 0:
229        return
230
231    # ponytail: a depth count, so a producer writing to this queue at the same
232    # moment can end the wait early and a consumer reading it can make it run
233    # to the timeout. The broker offers no reply to a requeue to wait on instead.
234    clock = asyncio.get_running_loop()
235    expires = clock.time() + wait
236    while True:
237        try:
238            if await connection.message_count(queue) >= before + len(declined):
239                return
240        except Exception:
241            return
242        if clock.time() >= expires:
243            log.warning(
244                "acemq: %d messages returned to %r had not shown up after %ss",
245                len(declined),
246                queue,
247                wait,
248            )
249            return
250        await asyncio.sleep(0.01)
251
252
253async def _move(
254    connection: Connection,
255    message: Delivery,
256    envelope: Envelope,
257    queue: str,
258    exchange: str,
259    routing_key: str | None,
260    restart: bool,
261) -> None:
262    """Republishes one message and then acknowledges the original.
263
264    That order, and not the other one. Acknowledging first would lose the
265    message whenever the publish failed; this way a failure in the gap replays
266    it twice, which is the right way round for a queue somebody is putting back
267    by hand.
268    """
269    going_back = envelope.with_(attempt=1, error="") if restart else envelope
270    key = message.routing_key if routing_key is None else routing_key
271
272    headers: dict[str, Any] = dict(going_back.to_headers(routing_key=key))
273    headers[HEADER_REPLAYED_FROM] = queue
274    headers[HEADER_REPLAYED_AT] = _replayed_at(datetime.now(timezone.utc))
275    headers[HEADER_REPLAY_COUNT] = _replays_so_far(envelope) + 1
276
277    try:
278        # Mandatory, because the original is acknowledged as soon as this
279        # returns: a destination nothing is bound to is confirmed and dropped by
280        # the broker, and without the return the replay would delete the last
281        # copy of a message it was asked to recover.
282        result = await connection.publish_raw(
283            exchange,
284            key,
285            Outbound(
286                body=message.body,
287                content_type=message.content_type or "",
288                message_id=going_back.id,
289                headers=headers,
290                persistent=True,
291                mandatory=True,
292            ),
293        )
294        if not result.routed:
295            raise PublishError(
296                going_back.id,
297                exchange,
298                key,
299                result.return_reason or "no queue is bound to receive it",
300                unroutable=True,
301            )
302    except Exception:
303        # Returned rather than dropped, and the replay stops. A replay that
304        # loses messages is worse than one that stops early.
305        await _return_quietly(message)
306        raise
307
308    await message.ack()
309
310
311async def _return_quietly(message: Delivery) -> None:
312    """Puts a message back without letting that failure hide the first one.
313
314    Logged rather than raised: by the time this is called the replay is already
315    stopping, and the message is one the broker returns itself when this
316    connection goes.
317    """
318    try:
319        await message.nack(True)
320    except Exception:
321        log.warning("acemq: could not return a message to the queue it was replayed from")
322
323
324def _replayed_at(when: datetime) -> str:
325    """The replay time as every AceMQ library writes it: milliseconds and ``Z``,
326    where ``isoformat()`` gives microseconds and ``+00:00``."""
327    return when.astimezone(timezone.utc).isoformat(timespec="milliseconds")[:-6] + "Z"
328
329
330def _replays_so_far(envelope: Envelope) -> int:
331    """How many times this message has been replayed already.
332
333    Read leniently, because the header may have been written by another
334    language's client or by a broker that renders integers as strings.
335    """
336    written = envelope.headers.get(HEADER_REPLAY_COUNT)
337    if isinstance(written, bool):
338        return 0
339    if isinstance(written, int):
340        return written
341    try:
342        return int(str(written))
343    except (TypeError, ValueError):
344        return 0
log = <Logger acemq (WARNING)>
HEADER_REPLAYED_FROM = 'acemq-replayed-from'
HEADER_REPLAYED_AT = 'acemq-replayed-at'
HEADER_REPLAY_COUNT = 'acemq-replay-count'
ReplayFilter: TypeAlias = Callable[[acemq_amqp.Envelope, bytes], bool]
@dataclass(frozen=True, slots=True)
class ReplayResult:
59@dataclass(frozen=True, slots=True)
60class ReplayResult:
61    """What a replay did, and why it stopped.
62
63    :param moved: how many messages were republished
64    :param skipped: how many the filter declined, and so left where they were
65    :param reason: ``drained``, ``limit`` or ``deadline``
66    """
67
68    moved: int
69    skipped: int
70    reason: str
71
72    def __str__(self) -> str:
73        return f"moved {self.moved}, skipped {self.skipped} ({self.reason})"

What a replay did, and why it stopped.

Parameters
  • moved: how many messages were republished
  • skipped: how many the filter declined, and so left where they were
  • reason: drained, limit or deadline
ReplayResult(moved: int, skipped: int, reason: str)
moved: int
skipped: int
reason: str
class ReplayError(acemq_amqp.errors.AceMQError):
76class ReplayError(AceMQError):
77    """A replay stopped because something failed.
78
79    It carries the :class:`ReplayResult` it had reached, because "it failed" and
80    "it failed after moving four hundred" are different things to be told at
81    three in the morning.
82    """
83
84    def __init__(self, result: ReplayResult, what: str) -> None:
85        self.result = result
86        super().__init__(f"acemq: {what} (after {result})")

A replay stopped because something failed.

It carries the ReplayResult it had reached, because "it failed" and "it failed after moving four hundred" are different things to be told at three in the morning.

ReplayError(result: ReplayResult, what: str)
84    def __init__(self, result: ReplayResult, what: str) -> None:
85        self.result = result
86        super().__init__(f"acemq: {what} (after {result})")
result
async def replay( connection: acemq_amqp.Connection, queue: str, *, exchange: str = '', routing_key: str | None = None, limit: int = 0, deadline: datetime.timedelta | None = None, only: Callable[[acemq_amqp.Envelope, bytes], bool] | None = None, restart: bool = True, return_wait: datetime.timedelta = datetime.timedelta(seconds=10)) -> ReplayResult:
 89async def replay(
 90    connection: Connection,
 91    queue: str,
 92    *,
 93    exchange: str = "",
 94    routing_key: str | None = None,
 95    limit: int = 0,
 96    deadline: timedelta | None = None,
 97    only: ReplayFilter | None = None,
 98    restart: bool = True,
 99    return_wait: timedelta = timedelta(seconds=10),
100) -> ReplayResult:
101    """Moves messages from a queue back onto an exchange::
102
103        result = await replay(
104            mq,
105            dead_letter_queue("orders.new"),
106            limit=500,
107            only=lambda envelope, body: "timeout" in envelope.error,
108        )
109        print(result)   # moved 137, skipped 363 (drained)
110
111    Each message is stamped with :data:`HEADER_REPLAYED_FROM`,
112    :data:`HEADER_REPLAYED_AT` and :data:`HEADER_REPLAY_COUNT`, so a consumer
113    that needs to treat a replayed message differently can, and one that does
114    not is unaffected.
115
116    :param connection: where to read from and publish to
117    :param queue: where the messages are now, usually a dead-letter queue
118    :param exchange: where they go back to, empty to publish to a queue by name
119    :param routing_key: what to publish them under. ``None`` keeps each
120        message's own, so a message goes back where it came from rather than
121        everywhere
122    :param limit: stop after this many. Zero means no limit, which against a
123        queue something is still writing to may mean it does not stop at all —
124        prefer a limit
125    :param deadline: stop after this long. ``None`` means no deadline
126    :param only: which messages to move. ``None`` moves all of them
127    :param restart: give each message a fresh set of attempts, clearing the
128        counter and the error that dead-lettered it. On by default because it is
129        what a replay is for: a message that arrives back on attempt five of a
130        five-attempt policy is dead-lettered again before a handler sees it, and
131        the operator who has just fixed the bug has moved two thousand messages
132        from one queue to the same queue. Turn it off to put back exactly what
133        was there — for an audit, or for a queue read by something that counts
134        attempts itself
135    :param return_wait: how long, once the pass is over, to wait for the
136        messages ``only`` passed over to show on the queue again. Ten seconds by
137        default. They are held unacknowledged for the whole pass, and the wait
138        reads the queue's depth, so a consumer draining the same queue at the
139        same time can make it run out; it then logs a warning and returns, and
140        the messages are still on the queue. Zero does not wait at all
141    :returns: what it did and why it stopped
142    :raises ReplayError: when reading or republishing failed. Whatever had
143        already been moved has been moved; the rest is still on the queue
144    """
145    if not queue:
146        raise ValueError("acemq: a replay needs a queue to read from")
147    if return_wait < timedelta(0):
148        raise ValueError("acemq: a replay's return_wait cannot be negative")
149
150    clock = asyncio.get_running_loop()
151    expires = None if deadline is None else clock.time() + deadline.total_seconds()
152    moved = 0
153    skipped = 0
154
155    # Messages the filter declines are held unsettled until the pass is over
156    # rather than returned one at a time. Returning one immediately does not
157    # work: the broker puts it back where it was, at the head of the queue, so
158    # the next pull hands over the same message and nothing behind it is ever
159    # looked at. Holding them takes them out of the way for the length of the
160    # pass, and because the broker is the one holding them, a crash returns them
161    # rather than losing them.
162    declined: list[Delivery] = []
163
164    try:
165        while True:
166            if limit > 0 and moved >= limit:
167                return ReplayResult(moved, skipped, "limit")
168            if expires is not None and clock.time() >= expires:
169                return ReplayResult(moved, skipped, "deadline")
170
171            try:
172                message = await connection.pull(queue)
173            except Exception as failure:
174                raise ReplayError(
175                    ReplayResult(moved, skipped, "failed"),
176                    f"cannot read {queue!r} to replay it: {failure}",
177                ) from failure
178
179            if message is None:
180                # Everything available has been offered. What is left is what
181                # this pass declined, and it goes back as the pass ends.
182                return ReplayResult(moved, skipped, "drained")
183
184            envelope = Envelope.from_headers(
185                message.headers, message.routing_key, message.message_id
186            )
187            if only is not None and not only(envelope, message.body):
188                skipped += 1
189                declined.append(message)
190                continue
191
192            try:
193                await _move(
194                    connection, message, envelope, queue, exchange, routing_key, restart
195                )
196            except Exception as failure:
197                raise ReplayError(
198                    ReplayResult(moved, skipped, "failed"),
199                    f"cannot republish a message from {queue!r}: {failure}",
200                ) from failure
201            moved += 1
202    finally:
203        await _return_declined(connection, queue, declined, return_wait.total_seconds())

Moves messages from a queue back onto an exchange::

result = await replay(
    mq,
    dead_letter_queue("orders.new"),
    limit=500,
    only=lambda envelope, body: "timeout" in envelope.error,
)
print(result)   # moved 137, skipped 363 (drained)

Each message is stamped with HEADER_REPLAYED_FROM, HEADER_REPLAYED_AT and HEADER_REPLAY_COUNT, so a consumer that needs to treat a replayed message differently can, and one that does not is unaffected.

Parameters
  • connection: where to read from and publish to
  • queue: where the messages are now, usually a dead-letter queue
  • exchange: where they go back to, empty to publish to a queue by name
  • routing_key: what to publish them under. None keeps each message's own, so a message goes back where it came from rather than everywhere
  • limit: stop after this many. Zero means no limit, which against a queue something is still writing to may mean it does not stop at all — prefer a limit
  • deadline: stop after this long. None means no deadline
  • only: which messages to move. None moves all of them
  • restart: give each message a fresh set of attempts, clearing the counter and the error that dead-lettered it. On by default because it is what a replay is for: a message that arrives back on attempt five of a five-attempt policy is dead-lettered again before a handler sees it, and the operator who has just fixed the bug has moved two thousand messages from one queue to the same queue. Turn it off to put back exactly what was there — for an audit, or for a queue read by something that counts attempts itself
  • return_wait: how long, once the pass is over, to wait for the messages only passed over to show on the queue again. Ten seconds by default. They are held unacknowledged for the whole pass, and the wait reads the queue's depth, so a consumer draining the same queue at the same time can make it run out; it then logs a warning and returns, and the messages are still on the queue. Zero does not wait at all :returns: what it did and why it stopped
Raises
  • ReplayError: when reading or republishing failed. Whatever had already been moved has been moved; the rest is still on the queue