Skip to content

Commit 441fe9f

Browse files
ansdmergify[bot]
authored andcommitted
Fix dead lettering
# What? This commit fixes #11159, #11160, #11173. # How? ## Background RabbitMQ allows to dead letter messages for four different reasons, out of which three reasons cause messages to be dead lettered automatically internally in the broker: (maxlen, expired, delivery_limit) and 1 reason is caused by an explicit client action (rejected). RabbitMQ also allows dead letter topologies. When a message is dead lettered, it is re-published to an exchange, and therefore zero to multiple target queues. These target queues can in turn dead letter messages. Hence it is possible to create a cycle of queues where messages get dead lettered endlessly, which is what we want to avoid. ## Alternative approach One approach to avoid such endless cycles is to use a similar concept of the TTL field of the IPv4 datagram, or the hop limit field of an IPv6 datagram. These fields ensure that IP packets aren't cicrulating forever in the Internet. Each router decrements this counter. If this counter reaches 0, the sender will be notified and the message gets dropped. We could use the same approach in RabbitMQ: Whenever a queue dead letters a message, a dead_letter_hop_limit field could be decremented. If this field reaches 0, the message will be dropped. Such a hop limit field could have a sensible default value, for example 32. The sender of the message could override this value. Likewise, the client rejecting a message could set a new value via the Modified outcome. Such an approach has multiple advantages: 1. No dead letter cycle detection per se needs to be performed within the broker which is a slight simplification to what we have today. 2. Simpler dead letter topologies. One very common use case is that clients re-try sending the message after some time by consuming from a dead-letter queue and rejecting the message such that the message gets republished to the original queue. Instead of requiring explicit client actions, which increases complexity, a x-message-ttl argument could be set on the dead-letter queue to automatically retry after some time. This is a big simplification because it eliminates the need of various frameworks that retry, such as https://docs.spring.io/spring-cloud-stream/reference/rabbit/rabbit_overview/rabbitmq-retry.html 3. No dead letter history information needs to be compressed because there is a clear limit on how often a message gets dead lettered. Therefore, the full history including timestamps of every dead letter event will be available to clients. Disadvantages: 1. Breaks a lot of clients, even for 4.0. ## 3.12 approach Instead of decrementing a counter, the approach up to 3.12 has been to drop the message if the message cycled automatically. A message cycled automatically if no client expliclity rejected the message, i.e. the mesage got dead lettered due to maxlen, expired, or delivery_limit, but not due to rejected. In this approach, the broker must be able to detect such cycles reliably. Reliably detecting dead letter cycles broke in 3.13 due to #11159 and #11160. To reliably detect cycles, the broker must be able to obtain the exact order of dead letter events for a given message. In 3.13.0 - 3.13.2, the order cannot exactly be determined because wall clock time is used to record the death time. This commit uses the same approach as done in 3.12: a list ordered by death recency is used with the most recent death at the head of the list. To not grow this list endlessly (for example when a client rejects the same message hundreds of times), this list should be compacted. This commit, like 3.12, compacts by tuple `{Queue, Reason}`: If this message got already dead lettered from this Queue for this Reason, then only a counter is incremented and the element is moved to the front of the list. ## Streams & AMQP 1.0 clients Dead lettering from a stream doesn't make sense because: 1. a client cannot reject a message from a stream since the stream must maintain the total order of events to be consumed by multiple clients. 2. TTL is implemented by Stream retention where only old Stream segments are automatically deleted (or archived in the future). 3. same applies to maxlen Although messages cannot be dead lettered **from** a stream, messages can be dead lettered **into** a stream. This commit provides clients consuming from a stream the death history: #11173 Additionally, this commit provides AMQP 1.0 clients the death history via message annotation `x-opt-deaths` which contains the same information as AMQP 0.9.1 header `x-death`. Both, storing the death history in a stream and providing death history to an AMQP 1.0 client, use the same encoding: a message annoation `x-opt-deaths` that contains an array of maps ordered by death recency. The information encoded is the same as in the AMQP 0.9.1 x-death header. Instead of providing an array of maps, a better approach could be to use an array of a custom AMQP death type, such as: ```xml <amqp name="rabbitmq"> <section name="custom-types"> <type name="death" class="composite" source="list"> <descriptor name="rabbitmq:death:list" code="0x00000000:0x000000255"/> <field name="queue" type="string" mandatory="true" label="the name of the queue the message was dead lettered from"/> <field name="reason" type="symbol" mandatory="true" label="the reason why this message was dead lettered"/> <field name="count" type="ulong" default="1" label="how many times this message was dead lettered from this queue for this reason"/> <field name="time" mandatory="true" type="timestamp" label="the first time when this message was dead lettered from this queue for this reason"/> <field name="exchange" type="string" default="" label="the exchange this message was published to before it was dead lettered for the first time from this queue for this reason"/> <field name="routing-keys" type="string" default="" multiple="true" label="the routing keys this message was published with before it was dead lettered for the first time from this queue for this reason"/> <field name="ttl" type="milliseconds" label="the time to live of this message before it was dead lettered for the first time from this queue for reason ‘expired’"/> </type> </section> </amqp> ``` However, encoding and decoding custom AMQP types that are nested within arrays which in turn are nested within the message annotation map can be difficult for clients and the broker. Also, each client will need to know the custom AMQP type. For now, therefore we use an array of maps. ## Feature flag The new way to record death information is done via mc annotation `deaths_v2`. Because old nodes do not know this new annotation, recording death information via mc annotation `deaths_v2` is hidden behind a new feature flag `message_containers_deaths_v2`. If this feature flag is disabled, a message will continue to use the 3.13.0 - 3.13.2 way to record death information in mc annotation `deaths`, or even the older way within `x-death` header directly if feature flag message_containers is also disabled. Only if feature flag `message_containers_deaths_v2` is enabled and this message hasn't been dead lettered before, will the new mc annotation `deaths_v2` be used. (cherry picked from commit 6b300a2) # Conflicts: # deps/rabbit/app.bzl # deps/rabbit/src/mc_amqp.erl # deps/rabbit/src/rabbit_core_ff.erl # deps/rabbit/test/amqp_client_SUITE.erl
1 parent 4735e01 commit 441fe9f

14 files changed

+5027
-224
lines changed

deps/rabbit/BUILD.bazel

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -386,7 +386,13 @@ rabbitmq_integration_suite(
386386
additional_beam = [
387387
":test_queue_utils_beam",
388388
],
389-
shard_count = 7,
389+
shard_count = 8,
390+
)
391+
392+
rabbitmq_integration_suite(
393+
name = "message_containers_deaths_v2_SUITE",
394+
size = "medium",
395+
shard_count = 1,
390396
)
391397

392398
rabbitmq_integration_suite(

deps/rabbit/app.bzl

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2153,3 +2153,78 @@ def test_suite_beam_files(name = "test_suite_beam_files"):
21532153
erlc_opts = "//:test_erlc_opts",
21542154
deps = ["//deps/amqp_client:erlang_app"],
21552155
)
2156+
<<<<<<< HEAD
2157+
=======
2158+
2159+
erlang_bytecode(
2160+
name = "test_event_recorder_beam",
2161+
testonly = True,
2162+
srcs = ["test/event_recorder.erl"],
2163+
outs = ["test/event_recorder.beam"],
2164+
app_name = "rabbit",
2165+
erlc_opts = "//:test_erlc_opts",
2166+
deps = ["//deps/rabbit_common:erlang_app"],
2167+
)
2168+
erlang_bytecode(
2169+
name = "amqp_auth_SUITE_beam_files",
2170+
testonly = True,
2171+
srcs = ["test/amqp_auth_SUITE.erl"],
2172+
outs = ["test/amqp_auth_SUITE.beam"],
2173+
app_name = "rabbit",
2174+
erlc_opts = "//:test_erlc_opts",
2175+
deps = ["//deps/amqp10_common:erlang_app", "//deps/amqp_client:erlang_app"],
2176+
)
2177+
erlang_bytecode(
2178+
name = "amqp_client_SUITE_beam_files",
2179+
testonly = True,
2180+
srcs = ["test/amqp_client_SUITE.erl"],
2181+
outs = ["test/amqp_client_SUITE.beam"],
2182+
app_name = "rabbit",
2183+
erlc_opts = "//:test_erlc_opts",
2184+
deps = ["//deps/amqp10_common:erlang_app", "//deps/amqp_client:erlang_app"],
2185+
)
2186+
erlang_bytecode(
2187+
name = "amqp_credit_api_v2_SUITE_beam_files",
2188+
testonly = True,
2189+
srcs = ["test/amqp_credit_api_v2_SUITE.erl"],
2190+
outs = ["test/amqp_credit_api_v2_SUITE.beam"],
2191+
app_name = "rabbit",
2192+
erlc_opts = "//:test_erlc_opts",
2193+
deps = ["//deps/amqp_client:erlang_app"],
2194+
)
2195+
erlang_bytecode(
2196+
name = "amqp_proxy_protocol_SUITE_beam_files",
2197+
testonly = True,
2198+
srcs = ["test/amqp_proxy_protocol_SUITE.erl"],
2199+
outs = ["test/amqp_proxy_protocol_SUITE.beam"],
2200+
app_name = "rabbit",
2201+
erlc_opts = "//:test_erlc_opts",
2202+
)
2203+
erlang_bytecode(
2204+
name = "amqp_system_SUITE_beam_files",
2205+
testonly = True,
2206+
srcs = ["test/amqp_system_SUITE.erl"],
2207+
outs = ["test/amqp_system_SUITE.beam"],
2208+
app_name = "rabbit",
2209+
erlc_opts = "//:test_erlc_opts",
2210+
deps = ["//deps/rabbit_common:erlang_app"],
2211+
)
2212+
erlang_bytecode(
2213+
name = "amqp_address_SUITE_beam_files",
2214+
testonly = True,
2215+
srcs = ["test/amqp_address_SUITE.erl"],
2216+
outs = ["test/amqp_address_SUITE.beam"],
2217+
app_name = "rabbit",
2218+
erlc_opts = "//:test_erlc_opts",
2219+
deps = ["//deps/amqp10_common:erlang_app", "//deps/rabbitmq_amqp_client:erlang_app"],
2220+
)
2221+
erlang_bytecode(
2222+
name = "message_containers_deaths_v2_SUITE_beam_files",
2223+
testonly = True,
2224+
srcs = ["test/message_containers_deaths_v2_SUITE.erl"],
2225+
outs = ["test/message_containers_deaths_v2_SUITE.beam"],
2226+
app_name = "rabbit",
2227+
erlc_opts = "//:test_erlc_opts",
2228+
deps = ["//deps/amqp_client:erlang_app", "//deps/rabbitmq_ct_helpers:erlang_app"],
2229+
)
2230+
>>>>>>> 6b300a2f34 (Fix dead lettering)

deps/rabbit/include/mc.hrl

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,3 @@
1-
-type death_key() :: {SourceQueue :: rabbit_misc:resource_name(), rabbit_dead_letter:reason()}.
2-
-type death_anns() :: #{first_time := non_neg_integer(), %% the timestamp of the first
3-
last_time := non_neg_integer(), %% the timestamp of the last
4-
ttl => OriginalExpiration :: non_neg_integer()}.
5-
-record(death, {exchange :: OriginalExchange :: rabbit_misc:resource_name(),
6-
routing_keys = [] :: OriginalRoutingKeys :: [rabbit_types:routing_key()],
7-
count = 0 :: non_neg_integer(),
8-
anns :: death_anns()}).
9-
10-
-record(deaths, {first :: death_key(),
11-
last :: death_key(),
12-
records = #{} :: #{death_key() := #death{}}}).
13-
14-
151
%% good enough for most use cases
162
-define(IS_MC(Msg), element(1, Msg) == mc andalso tuple_size(Msg) == 5).
173

@@ -26,3 +12,25 @@
2612
-define(ANN_RECEIVED_AT_TIMESTAMP, rts).
2713
-define(ANN_DURABLE, d).
2814
-define(ANN_PRIORITY, p).
15+
16+
-define(FF_MC_DEATHS_V2, message_containers_deaths_v2).
17+
18+
-type death_key() :: {SourceQueue :: rabbit_misc:resource_name(), rabbit_dead_letter:reason()}.
19+
-type death_anns() :: #{%% timestamp of the first time this message
20+
%% was dead lettered from this queue for this reason
21+
first_time := pos_integer(),
22+
%% timestamp of the last time this message
23+
%% was dead lettered from this queue for this reason
24+
last_time := pos_integer(),
25+
ttl => OriginalTtlHeader :: non_neg_integer()}.
26+
27+
-record(death, {exchange :: OriginalExchange :: rabbit_misc:resource_name(),
28+
routing_keys :: OriginalRoutingKeys :: [rabbit_types:routing_key(),...],
29+
%% how many times this message was dead lettered from this queue for this reason
30+
count :: pos_integer(),
31+
anns :: death_anns()}).
32+
33+
-record(deaths, {first :: death_key(), % redundant to mc annotations x-first-death-*
34+
last :: death_key(), % redundant to mc annotations x-last-death-*
35+
records :: #{death_key() := #death{}}
36+
}).

deps/rabbit/src/mc.erl

Lines changed: 100 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,8 @@
3232
convert/3,
3333
protocol_state/1,
3434
prepare/2,
35-
record_death/3,
35+
record_death/4,
3636
is_death_cycle/2,
37-
last_death/1,
3837
death_queue_names/1
3938
]).
4039

@@ -339,89 +338,103 @@ protocol_state(BasicMsg) ->
339338
mc_compat:protocol_state(BasicMsg).
340339

341340
-spec record_death(rabbit_dead_letter:reason(),
342-
SourceQueue :: rabbit_misc:resource_name(),
343-
state()) -> state().
341+
rabbit_misc:resource_name(),
342+
state(),
343+
environment()) -> state().
344344
record_death(Reason, SourceQueue,
345-
#?MODULE{protocol = _Mod,
346-
data = _Data,
347-
annotations = Anns0} = State)
348-
when is_atom(Reason) andalso is_binary(SourceQueue) ->
345+
#?MODULE{annotations = Anns0} = State,
346+
Env)
347+
when is_atom(Reason) andalso
348+
is_binary(SourceQueue) ->
349349
Key = {SourceQueue, Reason},
350350
#{?ANN_EXCHANGE := Exchange,
351351
?ANN_ROUTING_KEYS := RoutingKeys} = Anns0,
352352
Timestamp = os:system_time(millisecond),
353353
Ttl = maps:get(ttl, Anns0, undefined),
354-
355-
ReasonBin = atom_to_binary(Reason),
356-
DeathAnns = rabbit_misc:maps_put_truthy(ttl, Ttl, #{first_time => Timestamp,
357-
last_time => Timestamp}),
358-
case maps:get(deaths, Anns0, undefined) of
359-
undefined ->
360-
Ds = #deaths{last = Key,
361-
first = Key,
362-
records = #{Key => #death{count = 1,
363-
exchange = Exchange,
364-
routing_keys = RoutingKeys,
365-
anns = DeathAnns}}},
366-
Anns = Anns0#{<<"x-first-death-reason">> => ReasonBin,
354+
DeathAnns = rabbit_misc:maps_put_truthy(
355+
ttl, Ttl, #{first_time => Timestamp,
356+
last_time => Timestamp}),
357+
NewDeath = #death{exchange = Exchange,
358+
routing_keys = RoutingKeys,
359+
count = 1,
360+
anns = DeathAnns},
361+
Anns = case Anns0 of
362+
#{deaths := Deaths0} ->
363+
Deaths = case Deaths0 of
364+
#deaths{records = Rs0} ->
365+
Rs = maps:update_with(
366+
Key,
367+
fun(Death) ->
368+
update_death(Death, Timestamp)
369+
end,
370+
NewDeath,
371+
Rs0),
372+
Deaths0#deaths{last = Key,
373+
records = Rs};
374+
_ ->
375+
%% Deaths are ordered by recency
376+
case lists:keytake(Key, 1, Deaths0) of
377+
{value, {Key, D0}, Deaths1} ->
378+
D = update_death(D0, Timestamp),
379+
[{Key, D} | Deaths1];
380+
false ->
381+
[{Key, NewDeath} | Deaths0]
382+
end
383+
end,
384+
Anns0#{<<"x-last-death-reason">> := atom_to_binary(Reason),
385+
<<"x-last-death-queue">> := SourceQueue,
386+
<<"x-last-death-exchange">> := Exchange,
387+
deaths := Deaths};
388+
_ ->
389+
Deaths = case Env of
390+
#{?FF_MC_DEATHS_V2 := false} ->
391+
#deaths{last = Key,
392+
first = Key,
393+
records = #{Key => NewDeath}};
394+
_ ->
395+
[{Key, NewDeath}]
396+
end,
397+
ReasonBin = atom_to_binary(Reason),
398+
Anns0#{<<"x-first-death-reason">> => ReasonBin,
367399
<<"x-first-death-queue">> => SourceQueue,
368400
<<"x-first-death-exchange">> => Exchange,
369401
<<"x-last-death-reason">> => ReasonBin,
370402
<<"x-last-death-queue">> => SourceQueue,
371-
<<"x-last-death-exchange">> => Exchange
372-
},
373-
374-
State#?MODULE{annotations = Anns#{deaths => Ds}};
375-
#deaths{records = Rs} = Ds0 ->
376-
Death = #death{count = C,
377-
anns = DA} = maps:get(Key, Rs,
378-
#death{exchange = Exchange,
379-
routing_keys = RoutingKeys,
380-
anns = DeathAnns}),
381-
Ds = Ds0#deaths{last = Key,
382-
records = Rs#{Key =>
383-
Death#death{count = C + 1,
384-
anns = DA#{last_time => Timestamp}}}},
385-
Anns = Anns0#{deaths => Ds,
386-
<<"x-last-death-reason">> => ReasonBin,
387-
<<"x-last-death-queue">> => SourceQueue,
388-
<<"x-last-death-exchange">> => Exchange},
389-
State#?MODULE{annotations = Anns}
390-
end;
391-
record_death(Reason, SourceQueue, BasicMsg) ->
392-
mc_compat:record_death(Reason, SourceQueue, BasicMsg).
403+
<<"x-last-death-exchange">> => Exchange,
404+
deaths => Deaths}
405+
end,
406+
State#?MODULE{annotations = Anns};
407+
record_death(Reason, SourceQueue, BasicMsg, Env) ->
408+
mc_compat:record_death(Reason, SourceQueue, BasicMsg, Env).
393409

410+
update_death(#death{count = Count,
411+
anns = DeathAnns} = Death, Timestamp) ->
412+
Death#death{count = Count + 1,
413+
anns = DeathAnns#{last_time := Timestamp}}.
394414

395415
-spec is_death_cycle(rabbit_misc:resource_name(), state()) -> boolean().
416+
is_death_cycle(TargetQueue, #?MODULE{annotations = #{deaths := #deaths{records = Rs}}}) ->
417+
is_cycle_v1(TargetQueue, maps:keys(Rs));
396418
is_death_cycle(TargetQueue, #?MODULE{annotations = #{deaths := Deaths}}) ->
397-
is_cycle(TargetQueue, maps:keys(Deaths#deaths.records));
419+
is_cycle_v2(TargetQueue, Deaths);
398420
is_death_cycle(_TargetQueue, #?MODULE{}) ->
399421
false;
400422
is_death_cycle(TargetQueue, BasicMsg) ->
401423
mc_compat:is_death_cycle(TargetQueue, BasicMsg).
402424

425+
%% Returns death queue names ordered by recency.
403426
-spec death_queue_names(state()) -> [rabbit_misc:resource_name()].
404-
death_queue_names(#?MODULE{annotations = Anns}) ->
405-
case maps:get(deaths, Anns, undefined) of
406-
undefined ->
407-
[];
408-
#deaths{records = Records} ->
409-
proplists:get_keys(maps:keys(Records))
410-
end;
427+
death_queue_names(#?MODULE{annotations = #{deaths := #deaths{records = Rs}}}) ->
428+
proplists:get_keys(maps:keys(Rs));
429+
death_queue_names(#?MODULE{annotations = #{deaths := Deaths}}) ->
430+
lists:map(fun({{Queue, _Reason}, _Death}) ->
431+
Queue
432+
end, Deaths);
433+
death_queue_names(#?MODULE{}) ->
434+
[];
411435
death_queue_names(BasicMsg) ->
412436
mc_compat:death_queue_names(BasicMsg).
413437

414-
-spec last_death(state()) ->
415-
undefined | {death_key(), #death{}}.
416-
last_death(#?MODULE{annotations = Anns})
417-
when not is_map_key(deaths, Anns) ->
418-
undefined;
419-
last_death(#?MODULE{annotations = #{deaths := #deaths{last = Last,
420-
records = Rs}}}) ->
421-
{Last, maps:get(Last, Rs)};
422-
last_death(BasicMsg) ->
423-
mc_compat:last_death(BasicMsg).
424-
425438
-spec prepare(read | store, state()) -> state().
426439
prepare(For, #?MODULE{protocol = Proto,
427440
data = Data} = State) ->
@@ -431,24 +444,38 @@ prepare(For, State) ->
431444

432445
%% INTERNAL
433446

434-
%% if there is a death with a source queue that is the same as the target
447+
is_cycle_v2(TargetQueue, Deaths) ->
448+
case lists:splitwith(fun({{SourceQueue, _Reason}, #death{}}) ->
449+
SourceQueue =/= TargetQueue
450+
end, Deaths) of
451+
{_, []} ->
452+
false;
453+
{L, [H | _]} ->
454+
%% There is a cycle, but we only want to drop the message
455+
%% if the cycle is "fully automatic", i.e. without a client
456+
%% expliclity rejecting the message somewhere in the cycle.
457+
lists:all(fun({{_SourceQueue, Reason}, _Death}) ->
458+
Reason =/= rejected
459+
end, [H | L])
460+
end.
461+
462+
%% The desired v1 behaviour is the following:
463+
%% "If there is a death with a source queue that is the same as the target
435464
%% queue name and there are no newer deaths with the 'rejected' reason then
436-
%% consider this a cycle
437-
is_cycle(_Queue, []) ->
465+
%% consider this a cycle."
466+
%% However, the correct death order cannot be reliably determined in v1.
467+
%% deaths_v2 fixes this bug.
468+
is_cycle_v1(_Queue, []) ->
438469
false;
439-
is_cycle(_Queue, [{_Q, rejected} | _]) ->
470+
is_cycle_v1(_Queue, [{_Q, rejected} | _]) ->
440471
%% any rejection breaks the cycle
441472
false;
442-
is_cycle(Queue, [{Queue, Reason} | _])
473+
is_cycle_v1(Queue, [{Queue, Reason} | _])
443474
when Reason =/= rejected ->
444475
true;
445-
is_cycle(Queue, [_ | Rem]) ->
446-
is_cycle(Queue, Rem).
476+
is_cycle_v1(Queue, [_ | Rem]) ->
477+
is_cycle_v1(Queue, Rem).
447478

448479
set_received_at_timestamp(Anns) ->
449480
Millis = os:system_time(millisecond),
450481
Anns#{?ANN_RECEIVED_AT_TIMESTAMP => Millis}.
451-
452-
-ifdef(TEST).
453-
-include_lib("eunit/include/eunit.hrl").
454-
-endif.

0 commit comments

Comments
 (0)