message_delete: Fix flaky 'do_delete_messages' function.

This commit fixes a flake in `do_delete_messages`, because of
which `test_do_delete_messages_grouping_logic` test occasionally
failed due to nondeterministic ordering of "delete_message" events.

The root cause was that the dictionaries used to group private
and stream messages for deletion (`private_messages_by_recipient`
and `stream_messages_by_topic`) were not sorted before generating
the events. While the `message_ids` within each event were already
sorted, the order of the events themselves could vary based on
the insertion order of the dictionaries, especially when running
tests in different sequences.

We now sort both `private_messages_by_recipient` and
`stream_messages_by_topic` before emitting events, ensuring
consistent ordering.
This commit is contained in:
whilstsomebody
2025-06-20 02:40:53 +05:30
committed by Tim Abbott
parent 1ebfa6bae3
commit 01935c5be2

View File

@@ -120,15 +120,15 @@ def do_delete_messages(
recipient_id = message.recipient.id
private_messages_by_recipient[recipient_id].append(message)
for recipient_id, grouped_messages in private_messages_by_recipient.items():
for recipient_id, grouped_messages in sorted(private_messages_by_recipient.items()):
_process_grouped_messages_deletion(
realm, grouped_messages, stream=None, topic=None, acting_user=acting_user
)
for (
recipient_id,
topic_name,
), grouped_messages in stream_messages_by_recipient_and_topic.items():
(recipient_id, topic_name),
grouped_messages,
) in sorted(stream_messages_by_recipient_and_topic.items()):
if recipient_id not in stream_by_recipient_id:
stream_by_recipient_id[recipient_id] = Stream.objects.get(recipient_id=recipient_id)
stream = stream_by_recipient_id[recipient_id]