Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
message_send: Reduce query count for DirectMessageGroup sends.
bedoa99ac3049f02
diff --git a/zerver/actions/message_send.py b/zerver/actions/message_send.pyindex 75ef022cdec..55dde1be0b5 100644--- a/zerver/actions/message_send.py+++ b/zerver/actions/message_send.py@@ -262,6 +262,7 @@ def get_recipient_info(possibly_mentioned_user_ids: AbstractSet[int] = set(),possible_topic_wildcard_mention: bool = True,possible_stream_wildcard_mention: bool = True,+ dm_involved_user_ids: set[int] | None = None,) -> RecipientInfoResult:stream_push_user_ids: set[int] = set()stream_email_user_ids: set[int] = set()@@ -440,7 +441,15 @@ def get_recipient_info()elif recipient.type == Recipient.DIRECT_MESSAGE_GROUP:- message_to_user_id_set = set(get_direct_message_group_user_ids(recipient))+ if dm_involved_user_ids is not None:+ # For production path when sending a direct message+ # passing through check_message. This avoids an extra db query.+ message_to_user_id_set = dm_involved_user_ids+ else:+ # Other paths like:+ # Message edit via update_message_content.+ # Tests that bypass check_message.+ message_to_user_id_set = set(get_direct_message_group_user_ids(recipient))else:raise ValueError("Bad recipient type")@@ -673,6 +682,7 @@ def build_message_send_dict(no_previews: bool = False,user_group_membership_details: UserGroupMembershipDetails | None = None,sender_is_subscribed: bool | None = None,+ dm_involved_user_ids: set[int] | None = None,) -> SendMessageRequest:"""Returns a dictionary that can be passed into do_send_messages. Inproduction, this is always called by check_message, but some@@ -706,6 +716,7 @@ def build_message_send_dict(possibly_mentioned_user_ids=mention_data.get_user_ids(),possible_topic_wildcard_mention=mention_data.message_has_topic_wildcards(),possible_stream_wildcard_mention=mention_data.message_has_stream_wildcards(),+ dm_involved_user_ids=dm_involved_user_ids,)# Render our message_dicts.@@ -827,6 +838,7 @@ def build_message_send_dict(disable_external_notifications=disable_external_notifications,topic_participant_user_ids=topic_participant_user_ids,recipients_for_user_creation_events=recipients_for_user_creation_events,+ dm_involved_user_ids=dm_involved_user_ids,)return message_send_dict@@ -1191,7 +1203,11 @@ def do_send_messages(# Deliver events to the real-time push system, as well as# enqueuing any additional processing triggered by the message.- wide_message_dict = MessageDict.wide_dict(send_request.message, realm_id)+ wide_message_dict = MessageDict.wide_dict(+ send_request.message,+ realm_id,+ dm_involved_user_ids=send_request.dm_involved_user_ids,+ )send_request.message_url, send_request.message_link = get_message_url_and_link(send_request, wide_message_dict@@ -1854,6 +1870,10 @@ def check_message(if realm is None:realm = sender.realm+ # IDs of the DM sender and recipient users, deduplicated.+ # None for stream message.+ dm_involved_user_ids: set[int] | None = None+recipients_for_user_creation_events = Noneif addressee.is_stream():topic_name = addressee.topic_name()@@ -1928,6 +1948,8 @@ def check_message("JabberMirror",]+ dm_involved_user_ids = {user.id for user in recipient_users} | {sender.id}+check_sender_can_access_recipients(sender, recipient_users)recipients_for_user_creation_events = get_recipients_for_user_creation_events(@@ -2005,6 +2027,7 @@ def check_message(no_previews=no_previews,user_group_membership_details=user_group_membership_details,sender_is_subscribed=sender_is_subscribed,+ dm_involved_user_ids=dm_involved_user_ids,)if (diff --git a/zerver/lib/display_recipient.py b/zerver/lib/display_recipient.pyindex ee52be0ede9..cf5bc4375eb 100644--- a/zerver/lib/display_recipient.py+++ b/zerver/lib/display_recipient.py@@ -1,3 +1,4 @@+from collections.abc import Mappingfrom typing import TYPE_CHECKING, Optional, TypedDictfrom django.db.models import QuerySet@@ -132,10 +133,15 @@ def bulk_fetch_stream_names(def bulk_fetch_user_display_recipients(recipient_tuples: set[tuple[int, int, int]],+ recipient_dm_user_ids: Mapping[int, set[int]] = {},) -> dict[int, list[UserDisplayRecipient]]:"""Takes set of tuples of the form (recipient_id, recipient_type, recipient_type_id)Returns dict mapping recipient_id to corresponding display_recipient++ The participants of a DirectMessageGroup are fixed when it is created, so+ a caller that already knows them for some recipients can pass them in via+ dm_involved_user_ids to avoid looking them up again."""from zerver.models.recipients import bulk_get_direct_message_group_user_ids@@ -146,9 +152,16 @@ def bulk_fetch_user_display_recipients(get_recipient_id = lambda tup: tup[0]direct_message_group_recipient_ids = [get_recipient_id(tup) for tup in recipient_tuples]++ # Query only DirectMessageGroup participants who are not already loaded.user_ids_in_direct_message_groups = bulk_get_direct_message_group_user_ids(- direct_message_group_recipient_ids+ [+ recipient_id+ for recipient_id in direct_message_group_recipient_ids+ if recipient_id not in recipient_dm_user_ids+ ])+ user_ids_in_direct_message_groups.update(recipient_dm_user_ids)# Find all user ids whose UserProfiles we will need to fetch:user_ids_to_fetch: set[int] = set()@@ -172,6 +185,7 @@ def bulk_fetch_user_display_recipients(def bulk_fetch_display_recipients(recipient_tuples: set[tuple[int, int, int]],+ recipient_dm_user_ids: Mapping[int, set[int]] = {},) -> dict[int, DisplayRecipientT]:"""Takes set of tuples of the form (recipient_id, recipient_type, recipient_type_id)@@ -187,7 +201,7 @@ def bulk_fetch_display_recipients(stream_display_recipients = bulk_fetch_stream_names(stream_recipients)direct_message_display_recipients = bulk_fetch_user_display_recipients(- direct_message_recipients+ direct_message_recipients, recipient_dm_user_ids)# Glue the dicts together and return:diff --git a/zerver/lib/message.py b/zerver/lib/message.pyindex 6f5aabba6ce..edac7227577 100644--- a/zerver/lib/message.py+++ b/zerver/lib/message.py@@ -187,6 +187,8 @@ class SendMessageRequest:disable_external_notifications: bool = Falseautomatic_new_visibility_policy: int | None = Nonerecipients_for_user_creation_events: dict[UserProfile, set[int]] | None = None+ # None for a channel message or for caller that bypass check_message.+ dm_involved_user_ids: set[int] | None = Nonereminder_target_message_id: int | None = Nonereminder_note: str | None = None# Computed during do_send_messages, for the POST /messages response.diff --git a/zerver/lib/message_cache.py b/zerver/lib/message_cache.pyindex 22d32067df7..53c3831c7e7 100644--- a/zerver/lib/message_cache.py+++ b/zerver/lib/message_cache.py@@ -1,5 +1,5 @@import copy-from collections.abc import Iterable+from collections.abc import Iterable, Mappingfrom datetime import datetimefrom email.headerregistry import Addressfrom typing import Any, TypedDict@@ -134,7 +134,12 @@ class MessageDict:"""@staticmethod- def wide_dict(message: Message, realm_id: int | None = None) -> dict[str, Any]:+ def wide_dict(+ message: Message,+ realm_id: int | None = None,+ *,+ dm_involved_user_ids: set[int] | None = None,+ ) -> dict[str, Any]:"""The next two lines get the cacheable field relatedto our message object, with the side effect of@@ -150,7 +155,10 @@ class MessageDict:processor."""MessageDict.bulk_hydrate_sender_info([obj])- MessageDict.bulk_hydrate_recipient_info([obj])+ MessageDict.bulk_hydrate_recipient_info(+ [obj],+ {} if dm_involved_user_ids is None else {obj["recipient_id"]: dm_involved_user_ids},+ )return obj@@ -544,7 +552,10 @@ class MessageDict:obj["stream_id"] = recipient_type_id@staticmethod- def bulk_hydrate_recipient_info(objs: list[dict[str, Any]]) -> None:+ def bulk_hydrate_recipient_info(+ objs: list[dict[str, Any]],+ recipient_dm_user_ids: Mapping[int, set[int]] = {},+ ) -> None:recipient_tuples = { # We use set to eliminate duplicate tuples.(obj["recipient_id"],@@ -553,7 +564,7 @@ class MessageDict:)for obj in objs}- display_recipients = bulk_fetch_display_recipients(recipient_tuples)+ display_recipients = bulk_fetch_display_recipients(recipient_tuples, recipient_dm_user_ids)for obj in objs:MessageDict.hydrate_recipient_info(obj, display_recipients[obj["recipient_id"]])diff --git a/zerver/tests/test_channel_fetch.py b/zerver/tests/test_channel_fetch.pyindex 7cd3cae0daa..ba394ce8dae 100644--- a/zerver/tests/test_channel_fetch.py+++ b/zerver/tests/test_channel_fetch.py@@ -883,7 +883,7 @@ class GetSubscribersTest(ZulipTestCase):polonius.id,]- with self.assert_database_query_count(73):+ with self.assert_database_query_count(67):self.subscribe_via_post(self.user_profile,stream_names,diff --git a/zerver/tests/test_email_mirror.py b/zerver/tests/test_email_mirror.pyindex 46b81c43e0e..26cae503de2 100644--- a/zerver/tests/test_email_mirror.py+++ b/zerver/tests/test_email_mirror.py@@ -1336,7 +1336,7 @@ class TestMissedMessageEmailMessages(ZulipTestCase):othello, mm_address, "TestMissedMessageEmailMessages body")- with self.assert_database_query_count(23):+ with self.assert_database_query_count(21):process_message(incoming_valid_message)# confirm that Hamlet got the message@@ -1364,7 +1364,7 @@ class TestMissedMessageEmailMessages(ZulipTestCase):cordelia, mm_address, "TestMissedGroupDirectMessageEmailMessages body")- with self.assert_database_query_count(23):+ with self.assert_database_query_count(21):process_message(incoming_valid_message)# Confirm Iago and Othello received the message.diff --git a/zerver/tests/test_example.py b/zerver/tests/test_example.pyindex e80f660c4ec..2be2e167668 100644--- a/zerver/tests/test_example.py+++ b/zerver/tests/test_example.py@@ -365,7 +365,7 @@ class TestQueryCounts(ZulipTestCase):cordelia = self.example_user("cordelia")# when direct message group doesn't exist and should be created as part of the flow- with self.assert_database_query_count(24):+ with self.assert_database_query_count(22):self.send_personal_message(from_user=hamlet,to_user=cordelia,@@ -373,7 +373,7 @@ class TestQueryCounts(ZulipTestCase):)# when direct message group exists- with self.assert_database_query_count(18):+ with self.assert_database_query_count(16):self.send_personal_message(from_user=hamlet,to_user=cordelia,diff --git a/zerver/tests/test_message_send.py b/zerver/tests/test_message_send.pyindex c8f151bf59b..dc04dc9c1f7 100644--- a/zerver/tests/test_message_send.py+++ b/zerver/tests/test_message_send.py@@ -3010,7 +3010,7 @@ class PersonalMessageSendTest(ZulipTestCase):prospero = self.example_user("prospero")# A normal user sends a personal message.- with self.assert_database_query_count(24):+ with self.assert_database_query_count(22):self.send_personal_message(hamlet, cordelia)# Give guests limited user access.@@ -3021,17 +3021,17 @@ class PersonalMessageSendTest(ZulipTestCase):# A guest with limited user access sends a personal message# to another accessible user.- with self.assert_database_query_count(25):+ with self.assert_database_query_count(23):self.send_personal_message(polonius, hamlet)# A guest with limited user access sends a personal message# to themself.- with self.assert_database_query_count(21):+ with self.assert_database_query_count(19):self.send_personal_message(polonius, polonius)# A guest with limited user access sends a personal message# to another accessible guest.- with self.assert_database_query_count(22):+ with self.assert_database_query_count(20):self.send_personal_message(polonius, prospero)def test_group_direct_message(self) -> None:@@ -3059,12 +3059,12 @@ class PersonalMessageSendTest(ZulipTestCase):# A normal user sends the first message# to a new DirectMessageGroup.- with self.assert_database_query_count(28):+ with self.assert_database_query_count(26):self.send_group_direct_message(iago, recipients)# A normal user sends a message# to an existing DirectMessageGroup.- with self.assert_database_query_count(21):+ with self.assert_database_query_count(19):self.send_group_direct_message(iago, recipients)# Subscribe polonius to Verona to make the recipients@@ -3078,12 +3078,12 @@ class PersonalMessageSendTest(ZulipTestCase):# A guest with limited user access sends the first message# to a new DirectMessageGroup.- with self.assert_database_query_count(30):+ with self.assert_database_query_count(28):self.send_group_direct_message(polonius, recipients)# A guest with limited user access sends a message# to an existing DirectMessageGroup.- with self.assert_database_query_count(23):+ with self.assert_database_query_count(21):self.send_group_direct_message(polonius, recipients)def test_direct_message_initiator_group_setting(self) -> None:@@ -3126,7 +3126,7 @@ class PersonalMessageSendTest(ZulipTestCase):# Have the administrator send a message, and verify that allows the user to reply.self.send_personal_message(admin, user_profile)- with self.assert_database_query_count(19):+ with self.assert_database_query_count(17):self.send_personal_message(user_profile, admin)# Tests that user cannot initiate direct message thread in groups.@@ -3136,7 +3136,7 @@ class PersonalMessageSendTest(ZulipTestCase):# Have the administrator send a message to the direct message group, and verify# that allows the user to reply.self.send_group_direct_message(admin, direct_message_group_1)- with self.assert_database_query_count(20):+ with self.assert_database_query_count(18):self.send_group_direct_message(user_profile, direct_message_group_1)# We cannot sent to `direct_message_group_2` as no message has been sent to this group yet.@@ -3162,7 +3162,7 @@ class PersonalMessageSendTest(ZulipTestCase):user_group,acting_user=None,)- with self.assert_database_query_count(19):+ with self.assert_database_query_count(17):self.send_personal_message(user_profile, cordelia)# Test that query count decreases if setting is set to a system group.@@ -3176,7 +3176,7 @@ class PersonalMessageSendTest(ZulipTestCase):acting_user=None,)othello = self.example_user("othello")- with self.assert_database_query_count(23):+ with self.assert_database_query_count(21):self.send_personal_message(user_profile, othello)def test_direct_message_permission_group_setting(self) -> None:@@ -3204,7 +3204,7 @@ class PersonalMessageSendTest(ZulipTestCase):acting_user=None,)# Tests if the user is allowed to send to administrators.- with self.assert_database_query_count(24):+ with self.assert_database_query_count(22):self.send_personal_message(user_profile, admin)self.send_personal_message(admin, user_profile)# Tests if we can send messages to self irrespective of the value of the setting.@@ -3222,7 +3222,7 @@ class PersonalMessageSendTest(ZulipTestCase):# We can send to this direct message group as it has administrator as one of the# recipient.- with self.assert_database_query_count(24):+ with self.assert_database_query_count(22):self.send_group_direct_message(user_profile, direct_message_group)self.send_group_direct_message(admin, direct_message_group)@@ -3254,7 +3254,7 @@ class PersonalMessageSendTest(ZulipTestCase):with self.assertRaises(DirectMessagePermissionError):self.send_personal_message(cordelia, polonius)- with self.assert_database_query_count(19):+ with self.assert_database_query_count(17):self.send_personal_message(user_profile, cordelia)# Test that query count decreases if setting is set to a system group.@@ -3267,7 +3267,7 @@ class PersonalMessageSendTest(ZulipTestCase):members_group,acting_user=None,)- with self.assert_database_query_count(18):+ with self.assert_database_query_count(16):self.send_personal_message(user_profile, cordelia)do_change_realm_permission_group_setting(diff --git a/zerver/tests/test_signup.py b/zerver/tests/test_signup.pyindex 847aefea5d3..619c43c728b 100644--- a/zerver/tests/test_signup.py+++ b/zerver/tests/test_signup.py@@ -1068,7 +1068,7 @@ class LoginTest(ZulipTestCase):# to sending messages, such as getting the welcome bot, looking up# the alert words for a realm, etc.with (- self.assert_database_query_count(101),+ self.assert_database_query_count(99),self.assert_memcached_count(19),self.captureOnCommitCallbacks(execute=True),):diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.pyindex c28c733d5b4..5fea269ff9a 100644--- a/zerver/tests/test_users.py+++ b/zerver/tests/test_users.py@@ -1154,7 +1154,7 @@ class QueryCountTest(ZulipTestCase):prereg_user = PreregistrationUser.objects.get(email="[email protected]")with (- self.assert_database_query_count(99),+ self.assert_database_query_count(95),self.assert_memcached_count(24),self.capture_send_event_calls(expected_num_events=11) as events,):