From 9c39053d6f74e09b2aecb0d34d108ccec3132af6 Mon Sep 17 00:00:00 2001 From: Alan Guo Xiang Tan Date: Tue, 9 May 2023 10:37:12 +0800 Subject: [PATCH] FIX: Ensure order when moving chat messages to another channel (#21447) What is the problem? Previously, this was the query used to move change messages into another channel. ``` INSERT INTO chat_messages( chat_channel_id, user_id, last_editor_id, message, cooked, cooked_version, created_at, updated_at ) SELECT :destination_channel_id, user_id, last_editor_id, message, cooked, cooked_version, CLOCK_TIMESTAMP(), CLOCK_TIMESTAMP() FROM chat_messages WHERE id IN (:message_ids) RETURNING id ``` The problem is that this incorrectly assumes that the insertion will be based on the order of `message_ids`. However, that is not the case as PostgreSQL provides no such guarantee. Instead we need to explicitly order the messages to ensure the right order of insertion. This problem was discovered by a flaky test which exposed the non-guarantee order of insertion. --- plugins/chat/lib/chat/message_mover.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/plugins/chat/lib/chat/message_mover.rb b/plugins/chat/lib/chat/message_mover.rb index 03fc0be7013..9103b2bf832 100644 --- a/plugins/chat/lib/chat/message_mover.rb +++ b/plugins/chat/lib/chat/message_mover.rb @@ -111,6 +111,7 @@ module Chat message_ids: @ordered_source_message_ids, destination_channel_id: destination_channel.id, } + moved_message_ids = DB.query_single(<<~SQL, query_args) INSERT INTO chat_messages( chat_channel_id, user_id, last_editor_id, message, cooked, cooked_version, created_at, updated_at @@ -125,6 +126,7 @@ module Chat CLOCK_TIMESTAMP() FROM chat_messages WHERE id IN (:message_ids) + ORDER BY created_at ASC, id ASC RETURNING id SQL